#!/usr/bin/env python3
"""Poll SEC financials into a tidy CSV. Requires Python 3.10+ and httpx.

Run --help for options. Default: free calls only, no payments or automatic retries.
Keep the CSV and its .state.json together; use a single writer, never overlapping
runs. Files are individually atomic, not a two-file transaction. After a write
failure inspect both before resuming. Import CIK as text to keep leading zeros;
import untrusted company/source strings as text, not spreadsheet formulas.
Reported data, not investment advice.
"""
from __future__ import annotations

import argparse
import csv
import json
import math
import os
from pathlib import Path
import re
import sys
import tempfile
import time
from decimal import Decimal, InvalidOperation

import httpx

BASE_URL = "https://tanod.dev"
ROUTE = "/v1/finance/sec/financials"
COLUMNS = (
    "company_name", "cik", "ticker", "period", "currency", "period_end", "fiscal_year",
    "fiscal_period", "form", "accession", "metric", "is_null", "tag", "taxonomy", "value",
    "unit", "metric_form", "metric_fiscal_year", "metric_fiscal_period", "metric_period_start",
    "metric_period_end", "metric_filed", "metric_accession", "cached", "stale", "cache_seconds",
    "source", "note", "disclaimer",
)
CACHE_COLUMNS = {"cached", "stale", "cache_seconds"}


class PaymentRequired(Exception):
    """Stop the entire batch without retrying or making a payment."""


def payment_headers() -> dict[str, str]:
    """PLACEHOLDER: optionally return a credit-key header from your own secret manager.

    Header shape: Authorization: Bearer <YOUR_TANOD_CREDIT_KEY>
    Never put a key in this file, the CSV, command-line arguments, or logs.
    Returning an empty dict selects the free allowance. This example does not sign
    x402 payments, buy credits, top up balances, or retry a payment-required call.
    """
    return {}


def cell(value) -> str:
    if value is None:
        return ""
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, (dict, list)):
        return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return str(value)


def cache_interval(payload: dict) -> int:
    seconds = payload.get("cache_seconds")
    if type(seconds) is not int or seconds <= 0:
        raise ValueError("Response has no positive cache_seconds; refusing to guess a polling interval")
    return seconds


def flatten_financials(payload: dict) -> list[dict[str, str]]:
    """Map returned facts only; never derive values, periods, units, or missing quarters."""
    cache_interval(payload)
    rows = []
    for period in payload["periods"]:
        for metric, fact in sorted(period["metrics"].items()):
            values = {
                "company_name": payload.get("name"), "cik": payload["cik"], "ticker": payload.get("ticker"),
                "period": payload["period"], "currency": payload.get("currency"),
                "period_end": period["periodEnd"], "fiscal_year": period.get("fiscalYear"),
                "fiscal_period": period.get("fiscalPeriod"), "form": period.get("form"),
                "accession": period["accession"], "metric": metric, "is_null": fact is None,
                "cached": payload.get("cached"), "stale": payload.get("stale"),
                "cache_seconds": payload["cache_seconds"], "source": payload.get("source"),
                "note": payload.get("note"), "disclaimer": payload.get("disclaimer"),
            }
            if fact is not None:
                values.update({"tag": fact.get("tag"), "taxonomy": fact.get("taxonomy"),
                               "value": fact.get("value"), "unit": fact.get("unit")})
                for column, field in (
                    ("metric_form", "form"), ("metric_fiscal_year", "fiscalYear"),
                    ("metric_fiscal_period", "fiscalPeriod"), ("metric_period_start", "periodStart"),
                    ("metric_period_end", "periodEnd"), ("metric_filed", "filed"),
                    ("metric_accession", "accession"),
                ):
                    values[column] = fact.get(field)
            rows.append({column: cell(values.get(column)) for column in COLUMNS})
    return rows


def row_key(row: dict) -> tuple[str, ...]:
    return tuple(row[k] for k in ("cik", "period", "period_end", "metric"))


def read_rows(path: Path) -> dict[tuple[str, ...], dict]:
    if not path.exists():
        return {}
    with path.open(newline="", encoding="utf-8") as stream:
        reader = csv.DictReader(stream)
        if reader.fieldnames != list(COLUMNS):
            raise ValueError("Existing CSV columns differ; use a new output file")
        rows = {}
        for row in reader:
            key = row_key(row)
            if key in rows or None in row or any(v is None for v in row.values()):
                raise ValueError("Existing CSV contains duplicate or malformed rows")
            rows[key] = row
        return rows


def merge_rows(existing: dict, incoming: list[dict]) -> tuple[dict, int]:
    """Upsert the latest facts, retaining older periods that leave the requested window."""
    merged = dict(existing)
    changed = 0
    for row in incoming:
        key = row_key(row)
        old = existing.get(key)
        # A CIK-only response has ticker=null; do not erase a previously known ticker.
        if old and not row["ticker"]:
            row = {**row, "ticker": old["ticker"]}
        fact_columns = set(COLUMNS) - CACHE_COLUMNS - {"ticker"}
        if old is None or any(old[c] != row[c] for c in fact_columns):
            changed += 1
        merged[key] = row
    return merged, changed


def atomic_write(path: Path, write) -> None:
    name = None
    try:
        with tempfile.NamedTemporaryFile(mode="w", newline="", encoding="utf-8", dir=path.parent,
                                         prefix=path.name + ".", suffix=".tmp", delete=False) as stream:
            name = stream.name
            write(stream)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(name, path)
    finally:
        if name is not None and os.path.exists(name):
            os.unlink(name)


def write_rows(path: Path, rows: dict) -> None:
    def write(stream):
        writer = csv.DictWriter(stream, fieldnames=COLUMNS)
        writer.writeheader()
        writer.writerows(rows[key] for key in sorted(rows))
    atomic_write(path, write)


def request_key(body: dict) -> str:
    return json.dumps(body, sort_keys=True, separators=(",", ":"))


def read_schedule(path: Path) -> dict[str, float]:
    if not path.exists():
        return {}
    data = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(data, dict) or any(
        not isinstance(v, (int, float)) or isinstance(v, bool) or not math.isfinite(v) or v < 0
        for v in data.values()
    ):
        raise ValueError("Invalid polling state; restore the state file before polling again")
    return data


def live_price(client: httpx.Client) -> str:
    response = client.get(BASE_URL + "/openapi.json")
    response.raise_for_status()
    price = response.json()["paths"][ROUTE]["post"]["x-payment-info"]["price"]
    try:
        amount = Decimal(price["amount"])
    except InvalidOperation as exc:
        raise ValueError("Invalid price in live OpenAPI; no financials calls made") from exc
    if price.get("mode") != "fixed" or price.get("currency") != "USD" or not amount.is_finite() or amount < 0:
        raise ValueError("Expected a fixed USD price in live OpenAPI; no financials calls made")
    return f"USD {amount} per call (live OpenAPI; a payment-required response is authoritative)"


def poll_once(client: httpx.Client, bodies: list[dict], output: Path, interval: float,
              *, clock=time.time, announce=print) -> float:
    """One serial pass. Commit each success so a later 402 cannot discard earlier results."""
    state_path = output.with_name(output.name + ".state.json")
    schedule = read_schedule(state_path)
    rows = read_rows(output)
    due = [body for body in bodies if schedule.get(request_key(body), 0) <= clock()]
    if due:
        announce(live_price(client))
    for body in due:
        headers = payment_headers()
        using_credits = bool(headers)
        if not headers:
            headers = {"X-Tanod-Free": "1"}
        response = client.post(BASE_URL + ROUTE, json=body, headers=headers)
        if response.status_code == 402:
            reason = "credit balance insufficient or payment required" if using_credits else "free daily allowance exhausted or payment required"
            raise PaymentRequired(f"HTTP 402: {reason}. Stopped the entire batch; earlier CSV results are saved. "
                                  "No retry, payment, or top-up was attempted. See the live 402 for the current quote.")
        response.raise_for_status()
        payload = response.json()
        incoming = flatten_financials(payload)
        merged, changed = merge_rows(rows, incoming)
        if merged != rows:
            write_rows(output, merged)
        rows = merged
        # The response, not a copied cache constant, sets the minimum polling delay.
        schedule[request_key(body)] = clock() + max(interval, cache_interval(payload))
        atomic_write(state_path, lambda stream: json.dump(schedule, stream, sort_keys=True))
        announce(f"{payload['cik']}: {changed} changed metric row(s); {len(incoming) - changed} unchanged")
    return min(schedule[request_key(body)] for body in bodies)


def company_requests(tickers: list[str], ciks: list[str], period: str, limit: int) -> list[dict]:
    bodies = []
    for ticker in tickers:
        ticker = ticker.strip().upper()
        if not re.fullmatch(r"[A-Z][A-Z0-9./-]{0,9}", ticker):
            raise ValueError("Each --ticker must be a ticker symbol of at most 10 characters")
        bodies.append({"ticker": ticker, "period": period, "limit": limit})
    for cik in ciks:
        cik = cik.strip().upper().removeprefix("CIK")
        if not re.fullmatch(r"[0-9]{1,10}", cik) or int(cik) == 0:
            raise ValueError("Each --cik must be a positive CIK of at most 10 digits")
        bodies.append({"cik": cik.zfill(10), "period": period, "limit": limit})
    return list({request_key(body): body for body in bodies}.values())


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--ticker", action="append", default=[], help="Repeat for each ticker")
    parser.add_argument("--cik", action="append", default=[], help="Repeat for each CIK")
    parser.add_argument("--period", choices=("annual", "quarterly"), default="annual")
    parser.add_argument("--limit", type=int, choices=range(1, 21), default=4)
    parser.add_argument("--output", type=Path, default=Path("financials.csv"))
    parser.add_argument("--interval-seconds", type=float, default=86400,
                        help="Requested delay, clamped to each response's cache_seconds (default: daily)")
    parser.add_argument("--watch", action="store_true", help="Wait and repeat; otherwise run one due pass and exit")
    args = parser.parse_args(argv)
    if not math.isfinite(args.interval_seconds) or args.interval_seconds <= 0:
        parser.error("--interval-seconds must be positive and finite")
    try:
        bodies = company_requests(args.ticker, args.cik, args.period, args.limit)
        if not bodies:
            parser.error("supply at least one --ticker or --cik")
        with httpx.Client(timeout=90, follow_redirects=False, trust_env=False) as client:
            while True:
                next_poll = poll_once(client, bodies, args.output, args.interval_seconds)
                if not args.watch:
                    return 0
                time.sleep(max(0, next_poll - time.time()))
    except PaymentRequired as exc:
        print(str(exc), file=sys.stderr)
        return 2
    except KeyboardInterrupt:
        print("Stopped; completed companies remain saved.", file=sys.stderr)
        return 130
    except (httpx.HTTPError, OSError, ValueError, KeyError, TypeError) as exc:
        # Do not print request headers, credentials, or untrusted error bodies.
        print(f"Stopped ({type(exc).__name__}); no automatic retry. Check the response schema, files, or connection.",
              file=sys.stderr)
        return 1


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