"""Check pipeline health: recent ingest runs + local/remote alerts."""
from __future__ import annotations

import sys

import requests

from ingest_client import IngestClient
import alerts
import ops_config as cfg

RETAILER = {1: "PnP", 2: "Checkers", 3: "Woolworths", 4: "Spar"}


def main() -> int:
    print("=== Live worker status ===")
    try:
        resp = requests.get(
            f"{cfg.BASE_URL}/ingest/v1/status",
            headers={"X-Service-Key": cfg.require_service_key(), "Accept": "application/json"},
            timeout=15,
            verify=cfg.VERIFY_TLS,
        )
        st = resp.json().get("status")
        if not st:
            print("  (no heartbeat yet)")
        else:
            print(
                f"  stage={st.get('stage')} retailer={st.get('retailer') or '—'} "
                f"msg={st.get('message') or '—'} updated={st.get('updated_at')}"
            )
    except Exception as exc:
        print(f"  (could not fetch status: {exc})")

    print("\n=== Recent ingest runs (per retailer) ===")
    client = IngestClient()
    runs = client.list_runs()["runs"]
    seen: dict[int, dict] = {}
    for r in runs:
        rid = r["retailer_id"]
        if rid not in seen:
            seen[rid] = r
    for rid, r in sorted(seen.items()):
        print(
            f"  {RETAILER.get(rid, rid):<10} run #{r['id']} {r['status']:<16} "
            f"fetched={r['fetched']} applied={int(r['created'])+int(r['updated'])} "
            f"rejected={r['rejected']} started={r['started_at']}"
        )

    print("\n=== Ops pipeline alerts (latest 10) ===")
    try:
        resp = requests.get(
            f"{cfg.BASE_URL}/ingest/v1/alerts",
            headers={"X-Service-Key": cfg.require_service_key(), "Accept": "application/json"},
            params={"limit": 10},
            timeout=15,
            verify=cfg.VERIFY_TLS,
        )
        for a in resp.json().get("alerts", []):
            print(
                f"  {a.get('created_at')} [{a.get('severity')}] "
                f"{a.get('retailer') or '—'}/{a.get('stage') or '—'}: {a.get('message')}"
            )
    except Exception as exc:
        print(f"  (could not fetch Ops alerts: {exc})")

    print("\n=== Local worker alerts (latest 10) ===")
    local = alerts.recent_local(10)
    if not local:
        print("  (none)")
    for a in local:
        print(
            f"  {a.get('ts')} [{a.get('severity')}] "
            f"{a.get('retailer') or '—'}/{a.get('stage') or '—'}: {a.get('message')}"
        )

    errors = [a for a in local if a.get("severity") == "error"]
    return 1 if errors else 0


if __name__ == "__main__":
    sys.exit(main())
