#!/usr/bin/env python3
"""
Continuously download NOAA/SWPC GOES primary X-ray and differential proton
JSON feeds, and append only new rows to year-based CSV files.

Output files:
    <DIR_OUT>/<year>-GOEX-X-ray.csv
    <DIR_OUT>/<year>-GOES-DP.csv

The program polls once per minute by default.  If a new year starts, rows are
written automatically into a new yearly file.

This script is based on the user's uploaded GOES downloader, but it is adapted
for unattended logging instead of plotting.
"""

from __future__ import annotations

import argparse
import csv
import json
import os
import sys
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Dict, Iterable, List, Optional, Sequence, Tuple

import requests

# -----------------------------------------------------------------------------
# User-editable settings
# -----------------------------------------------------------------------------
DIR_OUT = "./GOES-Data"   # change this to your preferred output directory
POLL_INTERVAL_SECONDS = 60   # poll cadence
HTTP_TIMEOUT_SECONDS = 30    # download timeout

PROTON_URL = "https://services.swpc.noaa.gov/json/goes/primary/differential-protons-7-day.json"
XRAY_URL = "https://services.swpc.noaa.gov/json/goes/primary/xrays-7-day.json"

XRAY_FILENAME_TAG = "GOEX-X-ray"  # kept as requested by the user
PROTON_FILENAME_TAG = "GOES-DP"

TIME_COLUMN_CANDIDATES = ["time_tag", "time", "timestamp", "datetime", "date"]
CHANNEL_COLUMN_CANDIDATES = ["energy", "channel", "band", "range", "detector"]
SATELLITE_COLUMN_CANDIDATES = ["satellite", "satellite_id", "satellite_number"]


# -----------------------------------------------------------------------------
# Small data containers
# -----------------------------------------------------------------------------
@dataclass
class YearFileState:
    max_time: Optional[datetime] = None
    keys_at_max_time: set[str] = field(default_factory=set)
    header: List[str] = field(default_factory=list)


# -----------------------------------------------------------------------------
# Generic helpers
# -----------------------------------------------------------------------------
def download_json(url: str, timeout: int = HTTP_TIMEOUT_SECONDS):
    response = requests.get(
        url,
        timeout=timeout,
        headers={"User-Agent": "goes-xray-dp-logger/1.0"},
    )
    response.raise_for_status()
    return response.json()


def ensure_list_payload(data):
    """Return the first list-of-dicts payload found."""
    if isinstance(data, list):
        return data
    if isinstance(data, dict):
        for value in data.values():
            if isinstance(value, list) and value and isinstance(value[0], dict):
                return value
    raise ValueError(f"Unexpected JSON structure: {type(data)!r}")


def find_time_column(columns: Sequence[str]) -> Optional[str]:
    for name in TIME_COLUMN_CANDIDATES:
        if name in columns:
            return name
    for name in columns:
        if "time" in name.lower():
            return name
    return None


def find_first_present(columns: Sequence[str], candidates: Sequence[str]) -> Optional[str]:
    for candidate in candidates:
        if candidate in columns:
            return candidate
    return None


def parse_time_value(value: str) -> Optional[datetime]:
    if value is None:
        return None
    text = str(value).strip()
    if not text:
        return None

    # NOAA JSON uses ISO timestamps with trailing Z.
    if text.endswith("Z"):
        text = text[:-1] + "+00:00"

    try:
        dt = datetime.fromisoformat(text)
    except ValueError:
        return None

    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    else:
        dt = dt.astimezone(timezone.utc)
    return dt


def json_safe_value(value):
    if value is None:
        return ""
    if isinstance(value, (str, int, float, bool)):
        return value
    return json.dumps(value, sort_keys=True)


def normalize_records(records: Iterable[dict]) -> Tuple[List[dict], str]:
    records = list(records)
    if not records:
        return [], "time_tag"

    time_col = find_time_column(list(records[0].keys()))
    if time_col is None:
        raise ValueError(f"Could not find a time column in columns: {list(records[0].keys())}")

    normalized: List[dict] = []
    for row in records:
        dt = parse_time_value(row.get(time_col))
        if dt is None:
            continue

        new_row = {key: json_safe_value(value) for key, value in row.items()}
        new_row[time_col] = dt.isoformat().replace("+00:00", "Z")
        new_row["year"] = dt.year
        new_row["time_utc"] = dt.isoformat().replace("+00:00", "Z")
        normalized.append(new_row)

    normalized.sort(key=lambda r: r[time_col])
    return normalized, time_col


def build_row_key(row: dict, time_col: str) -> str:
    parts = [str(row.get(time_col, ""))]
    for name in CHANNEL_COLUMN_CANDIDATES:
        if name in row:
            parts.append(f"{name}={row.get(name, '')}")
    for name in SATELLITE_COLUMN_CANDIDATES:
        if name in row:
            parts.append(f"{name}={row.get(name, '')}")
    return "|".join(parts)


def csv_path_for_year(dir_out: str, year: int, kind: str) -> str:
    tag = XRAY_FILENAME_TAG if kind == "xray" else PROTON_FILENAME_TAG
    return os.path.join(dir_out, f"{year}-{tag}.csv")


def read_existing_state(path: str, time_col: str) -> YearFileState:
    state = YearFileState()
    if not os.path.exists(path):
        return state

    with open(path, "r", newline="", encoding="utf-8") as fh:
        reader = csv.DictReader(fh)
        if reader.fieldnames:
            state.header = list(reader.fieldnames)

        for row in reader:
            dt = parse_time_value(row.get(time_col, ""))
            if dt is None:
                continue
            key = build_row_key(row, time_col)
            if state.max_time is None or dt > state.max_time:
                state.max_time = dt
                state.keys_at_max_time = {key}
            elif dt == state.max_time:
                state.keys_at_max_time.add(key)

    return state


def merge_headers(existing: Sequence[str], new_rows: Sequence[dict]) -> List[str]:
    header: List[str] = list(existing)
    seen = set(header)
    for row in new_rows:
        for key in row.keys():
            if key not in seen:
                header.append(key)
                seen.add(key)
    return header


def rewrite_csv_with_new_header(path: str, header: Sequence[str]) -> None:
    existing_rows: List[dict] = []
    if os.path.exists(path):
        with open(path, "r", newline="", encoding="utf-8") as fh:
            reader = csv.DictReader(fh)
            for row in reader:
                existing_rows.append(row)

    tmp_path = path + ".tmp"
    with open(tmp_path, "w", newline="", encoding="utf-8") as fh:
        writer = csv.DictWriter(fh, fieldnames=list(header), extrasaction="ignore")
        writer.writeheader()
        for row in existing_rows:
            writer.writerow({name: row.get(name, "") for name in header})

    os.replace(tmp_path, path)


def append_rows(path: str, rows: Sequence[dict], state: YearFileState) -> None:
    if not rows:
        return

    os.makedirs(os.path.dirname(path), exist_ok=True)

    target_header = merge_headers(state.header, rows)
    if state.header != target_header:
        rewrite_csv_with_new_header(path, target_header)
        state.header = target_header

    file_exists = os.path.exists(path) and os.path.getsize(path) > 0
    with open(path, "a", newline="", encoding="utf-8") as fh:
        writer = csv.DictWriter(fh, fieldnames=state.header, extrasaction="ignore")
        if not file_exists:
            writer.writeheader()
        for row in rows:
            writer.writerow({name: row.get(name, "") for name in state.header})


def split_new_rows_by_year(
    rows: Sequence[dict],
    time_col: str,
    year_states: Dict[int, YearFileState],
) -> Dict[int, List[dict]]:
    grouped: Dict[int, List[dict]] = {}

    for row in rows:
        dt = parse_time_value(row.get(time_col, ""))
        if dt is None:
            continue
        year = dt.year
        state = year_states.setdefault(year, YearFileState())
        key = build_row_key(row, time_col)

        is_new = False
        if state.max_time is None or dt > state.max_time:
            is_new = True
        elif dt == state.max_time and key not in state.keys_at_max_time:
            is_new = True

        if not is_new:
            continue

        grouped.setdefault(year, []).append(row)

        if state.max_time is None or dt > state.max_time:
            state.max_time = dt
            state.keys_at_max_time = {key}
        elif dt == state.max_time:
            state.keys_at_max_time.add(key)

    return grouped


# -----------------------------------------------------------------------------
# Logger class
# -----------------------------------------------------------------------------
class GOESLogger:
    def __init__(self, dir_out: str):
        self.dir_out = dir_out
        self.states: Dict[str, Dict[int, YearFileState]] = {"xray": {}, "proton": {}}

    def _get_state(self, kind: str, year: int, time_col: str) -> YearFileState:
        per_kind = self.states[kind]
        if year not in per_kind:
            path = csv_path_for_year(self.dir_out, year, kind)
            per_kind[year] = read_existing_state(path, time_col)
        return per_kind[year]

    def _prepare_states_for_rows(self, kind: str, years: Iterable[int], time_col: str) -> None:
        for year in years:
            self._get_state(kind, year, time_col)

    def _process_kind(self, *, kind: str, url: str) -> int:
        payload = ensure_list_payload(download_json(url))
        rows, time_col = normalize_records(payload)
        if not rows:
            return 0

        years = sorted({int(row["year"]) for row in rows})
        self._prepare_states_for_rows(kind, years, time_col)

        grouped = split_new_rows_by_year(rows, time_col, self.states[kind])
        total_written = 0
        for year, out_rows in sorted(grouped.items()):
            path = csv_path_for_year(self.dir_out, year, kind)
            state = self.states[kind][year]
            append_rows(path, out_rows, state)
            total_written += len(out_rows)
        return total_written

    def poll_once(self) -> Tuple[int, int]:
        xray_written = self._process_kind(kind="xray", url=XRAY_URL)
        proton_written = self._process_kind(kind="proton", url=PROTON_URL)
        return xray_written, proton_written


# -----------------------------------------------------------------------------
# Main loop
# -----------------------------------------------------------------------------
def seconds_to_next_minute(poll_seconds: int) -> float:
    if poll_seconds <= 0:
        return 0.0
    now = time.time()
    remainder = now % poll_seconds
    wait = poll_seconds - remainder
    if wait <= 0:
        wait = poll_seconds
    return wait


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Continuously append GOES X-ray and differential proton data to yearly CSV files."
    )
    parser.add_argument("--dirout", default=DIR_OUT, help="Output directory. Default is DIR_OUT at top of script.")
    parser.add_argument("--interval", type=int, default=POLL_INTERVAL_SECONDS, help="Polling interval in seconds.")
    parser.add_argument("--timeout", type=int, default=HTTP_TIMEOUT_SECONDS, help="HTTP timeout in seconds.")
    parser.add_argument("--once", action="store_true", help="Run one polling cycle and exit.")
    parser.add_argument(
        "--no-align",
        action="store_true",
        help="Do not align sleeping to the next interval boundary.",
    )
    return parser.parse_args()


def main() -> int:
    global HTTP_TIMEOUT_SECONDS

    args = parse_args()
    HTTP_TIMEOUT_SECONDS = args.timeout

    logger = GOESLogger(dir_out=args.dirout)
    os.makedirs(args.dirout, exist_ok=True)

    print(f"Writing GOES files into: {args.dirout}")
    print(f"X-ray files:   <year>-{XRAY_FILENAME_TAG}.csv")
    print(f"Proton files:  <year>-{PROTON_FILENAME_TAG}.csv")

    while True:
        stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
        try:
            xray_n, proton_n = logger.poll_once()
            print(f"[{stamp}] appended X-ray rows: {xray_n}, proton rows: {proton_n}")
        except requests.RequestException as exc:
            print(f"[{stamp}] network/download error: {exc}", file=sys.stderr)
        except Exception as exc:
            print(f"[{stamp}] processing error: {exc}", file=sys.stderr)

        if args.once:
            break

        if args.no_align:
            time.sleep(max(1, args.interval))
        else:
            time.sleep(seconds_to_next_minute(args.interval))

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
