#!/usr/bin/env python
import os, sys, glob, subprocess, shutil
from datetime import datetime, timedelta
import re, string
import numpy as np
from satellite_info import env_paths, sat_ant_info
from rt_file_reproc import check_missed_leoorb
import yaml


def update_yaml_file(template_file, output_file, satant_list, replace=False):
    """
    Update 'satant' in YAML as a list of strings.

    Parameters
    ----------
    template_file : str
        Input YAML template
    output_file : str
        Output YAML file
    satant_list : list[str]
        Example:
            ["05_02=20260510T02:45:00",
             "05_02=20260510T03:15:00"]
    replace : bool
        True  -> overwrite existing satant
        False -> append to existing satant
    """

    # Load YAML
    with open(template_file, "r") as f:
        config = yaml.safe_load(f) or {}

    # Normalize existing satant ? list[str]
    existing = []
    if "satant" in config:
        if isinstance(config["satant"], dict):
            existing = [f"{k}={v}" for k, v in config["satant"].items()]
        elif isinstance(config["satant"], list):
            existing = list(config["satant"])

    # Update
    config["satant"] = satant_list if replace else existing + satant_list

    # Write YAML
    with open(output_file, "w") as f:
        yaml.dump(config, f, sort_keys=False)

    return config


# ----------------------------------------------------------------------
# Argument parsing
# ----------------------------------------------------------------------
def parse_args():
    import argparse
    parser = argparse.ArgumentParser(
        description="Main Program arguments"
    )
   
    parser.add_argument("-t","--datetime", help = "%Y-%m-%dT%H:%M:%S")
    parser.add_argument("-v","--verbose", action='store_true',  help="print info for debug")

    parser.add_argument("-o", "--yaml-output", type=str, default='updated.yaml', help="updated config yaml file")
    parser.add_argument("-i", "--yaml-input", type=str, default='rt.yaml.template', help="input config yaml file")

    return parser.parse_args()

    
if __name__ == "__main__":

    args = parse_args()
    yaml_in =   args.yaml_input
    yaml_out =  args.yaml_output
    # Load YAML
    with open(yaml_in, "r") as f:
        config = yaml.safe_load(f) or {}

    # Time window
    window_minutes = config['reproc_segment_minutes']
    total_minutes = window_minutes 
    ddt = datetime.strptime(args.datetime, "%Y-%m-%dT%H:%M:%S")
    if total_minutes < 0:
       t_start = ddt + timedelta(minutes=total_minutes)
       t_end   = ddt
    else:
       t_start = ddt ; t_end   = ddt + timedelta(minutes=total_minutes)

    tstart = t_start.strftime("%Y%m%dT%H%M%S")
    tend = t_end.strftime("%Y%m%dT%H%M%S")
    mission = config['leo']['mission']
    satidx = config['leo']['satidx'] ; antidx = config['leo']['antidx']
    umd_repo = config['leo']['rnx_repo_root']
    print(tstart, tend)

    verbose = args.verbose
    #print(mission, verbose)
    satant_list = check_missed_leoorb(mission, t_start, t_end, satidx=satidx, antidx=antidx, umd_repo = umd_repo )
    if not verbose:
      update_yaml_file( yaml_in, yaml_out, satant_list,replace=True)
    else:
      print(satant_list)

