import os
import pandas as pd
import numpy as np
import subprocess

import montera.titan_utils as tu

csv_fname = 'time_summary.csv'

if os.path.isfile(csv_fname):
    df = pd.read_csv(csv_fname)
else:
    df = pd.DataFrame([])

records = []
for root, dirs, files in os.walk("."):
    #path = root.split(os.sep)
    for f in files:
        full_path = os.path.join(root, f)
        if not df.empty and full_path in df.file.values:
            print(f'skipping {full_path}')
            continue

        if f.endswith('all.T04'):
            print('----------------')
            print(f'processing {full_path}')
            result = subprocess.run(
                ['viewdat', '-i', full_path],
                text=True,
                capture_output=True,
                )
            #print(result.stdout)
            for line in result.stdout.split('\n'):
                if 'First time tag' in line:
                    ls = line.split()
                    print(f'{ls=}')
                    #print(ls[4], ls[5], ls[10], ls[11])
                    if ls[4] == '-0.001' or len(ls) < 10:
                        records.append({
                            'file': full_path,
                            'start_week': np.nan,
                            'start_time': np.nan,
                            'stop_week': np.nan,
                            'stop_time': np.nan,
                            })
                    else:
                            records.append({
                                'file': full_path,
                                'start_week': float(ls[4]),
                                'start_time': float(ls[5]),
                                'stop_week': float(ls[10]),
                                'stop_time': float(ls[11]),
                                })

        if f.endswith('TitanPlayer_NavSoln.hud'):
            df = tu.hud2df(full_path)
            print('----------------')
            print(full_path)
            #print(df)

            records.append({
                'file': full_path,
                'start_week': int(df.iloc[0].GPS_Cycle),
                'start_time': float(df.iloc[0].GPS_Sec),
                'stop_week': int(df.iloc[-1].GPS_Cycle),
                'stop_time': float(df.iloc[-1].GPS_Sec),
                })

        df = pd.DataFrame(records)
        df.to_csv(csv_fname, index=False)

print(df)
