import pandas as pd
import sys
import subprocess
import os

root_dir = "."

sn_to_name = {
        '6348C01835': 'EB79',
        '6348C01910': 'EB81',
        '6221C43829': 'BX992',
        }

"""
# Unzip
for root, dirs, files in os.walk(root_dir):
    for f in files:
        full_path = os.path.join(root, f)
        if not os.path.isfile(full_path):
            continue
        if not f.endswith('.zip'):
            continue
        print(f'unzip {full_path}')
        subprocess.run(['unzip', f], cwd=root)
        print(f'rm    {full_path}')
        os.remove(full_path)

# Change T04 names to include Judo SN
for root, dirs, files in os.walk(root_dir):
    for f in files:
        full_path = os.path.join(root, f)
        if not os.path.isfile(full_path):
            continue
        for sn in sn_to_name.keys():
            if f.startswith(sn) and f.endswith('T04'):
                fnew = f'{sn_to_name[sn]}_{f}'
                print(f'{full_path} -> {fnew}')
                new_path = os.path.join(root, fnew)
                os.rename(full_path, new_path)

# Move T04 files to  gnss-diff daily dirs
for root, dirs, files in os.walk(root_dir):
    for f in files:
        full_path = os.path.join(root, f)
        if full_path.startswith(f'{root_dir}{os.sep}24') and f.endswith('T04'):
            base_path = root.split(os.sep)[1]
            new_path = os.path.join(root_dir, base_path, f)
            if full_path != new_path:
                print(f'{full_path} -> {new_path}')
                os.rename(full_path, new_path)
sys.exit(0)
"""

# Move to Montana style directories
items = os.listdir(root_dir)
for item in items:
    if os.path.isdir(item):
        #full_path = os.path.join(root, d)
        #if os.path.isdir(full_path) and f.startswith('24'):
        print(f'{item=}')
        os.makedirs(os.path.join(item, 'gnss', 'data'), exist_ok=True)

        sub_items = os.listdir(item)
        for sub_item in sub_items:
            full_path = os.path.join(root_dir, item, sub_item)
            if os.path.isfile(full_path) and sub_item.endswith('T04'):
            #if os.path.isdir(full_path) and sub_item != 'data':
                dev = sub_item.split('_')[0]
                new_path = os.path.join(root_dir, item, 'data', 'gnss', dev, sub_item)

                new_dir = new_path.split(os.sep)
                n = 0
                for d in new_dir:
                    if d == dev:
                        break
                    n += 1
                #print(new_dir[0:n+1])
                new_dir = os.path.join(*new_dir[0:n+1])
                #print(f'{new_dir=}')

                print(f'{full_path} -> {new_path}')
                os.makedirs(new_dir, exist_ok=True)
                os.rename(full_path, new_path)
