
# In:
# /net/capacitor5/volume1/main/JammerTest2025/plannedTests/
# there the following files:
# plan-monday-2025-09-15.json
# plan-tuesday-2025-09-16.json
# plan-wednesday-2025-09-17.json
# plan-thursday-2025-09-18.json
# plan-friday-2025-09-19.json
# 
# these files contain test plans for different days.
# This script reads the appropriate file for a given date,
# and extracts the test times for a specified location, converting
# the local time to GPS time.

import argparse
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path

BASE_PLAN_PATH = Path("/net/capacitor5/volume1/main/JammerTest2025/asRunTests")

# Times are in Norway local time (UTC+2)
LOCAL_OFFSET = timedelta(hours=2)
GPS_EPOCH = datetime(1980, 1, 6)
GPS_WEEK_SECONDS = 7 * 24 * 3600
LEAP_SECONDS = 18

def _utc_to_gps(dt_utc):
    delta = dt_utc - GPS_EPOCH + timedelta(seconds=LEAP_SECONDS)
    total_seconds = delta.total_seconds()
    week = int(total_seconds // GPS_WEEK_SECONDS)
    seconds = total_seconds - week * GPS_WEEK_SECONDS
    return {"week": week, "seconds": int(round(seconds))}

def _norway_to_utc(dt_str):
    dt_local = datetime.fromisoformat(dt_str)
    dt_local -= LOCAL_OFFSET
    return dt_local

def _resolve_plan_path(year, month, day):
    date_obj = datetime(year, month, day)
    weekday = date_obj.strftime("%A").lower()
    filename = f"asRun-{weekday}-{year:04d}-{month:02d}-{day:02d}.json"
    plan_path = BASE_PLAN_PATH / filename
    if not plan_path.exists():
        raise FileNotFoundError(f"Plan file not found: {plan_path}")
    return plan_path


def get_test_plan_times(year, month, day, location=None):
    plan_path = _resolve_plan_path(year, month, day)
    with plan_path.open("r", encoding="utf-8") as handle:
        payload = json.load(handle)

    locations = payload.get("locations")
    if not isinstance(locations, list):
        raise ValueError("Plan JSON is missing 'locations' array")

    results = []
    for loc in locations:
        if not isinstance(loc, dict):
            continue

        loc_name = loc.get("location_name")
        if location is not None and loc_name != location:
            continue

        tests = loc.get("tests", [])
        if not isinstance(tests, list):
            continue

        for test in tests:
            if not isinstance(test, dict):
                continue

            test_id = test.get("test_id")

            # Briefing
            #if(test_id.startswith("0")):
            #    continue

            start_local = test.get("start_time")
            end_local = test.get("end_time")
            if not all((test_id, start_local, end_local)):
                continue

            #start_utc = _norway_to_utc(start_local)
            #end_utc = _norway_to_utc(end_local)
            start_utc = datetime.fromisoformat(start_local)
            end_utc = datetime.fromisoformat(end_local)


            results.append(
                {
                    "test_id": test_id,
                    "start_time": start_utc.isoformat(),
                    "end_time": end_utc.isoformat(),
                    "start_time_gps": _utc_to_gps(start_utc),
                    "end_time_gps": _utc_to_gps(end_utc)
                }
            )

    return results

def _parse_date_arg(date_str):
    try:
        dt = datetime.strptime(date_str, "%Y-%m-%d")
        return dt.year, dt.month, dt.day
    except ValueError as exc:
        raise argparse.ArgumentTypeError("Date must be in YYYY-MM-DD format") from exc

def main():
    parser = argparse.ArgumentParser(description="Print test plan times for a given date and area")
    parser.add_argument("date", help="Test date in YYYY-MM-DD format")
    parser.add_argument("area", help="AM location name (1,2, or 3)")
    args = parser.parse_args()

    args.area = f"Test Area {args.area}"
    year, month, day = _parse_date_arg(args.date)
    results = get_test_plan_times(year, month, day, args.area)
    for this_test in results:
        print(
            this_test["test_id"],
            this_test["start_time_gps"]["seconds"],
            this_test["end_time_gps"]["seconds"],
        )


if __name__ == "__main__":
    main()


