#!/usr/bin/env python3
"""
CE Trend Radar — Source Health Checker
Run: python3 scripts/check-source-health.py
Outputs a status report for all configured sources.
"""

import json
import sys
import time
import urllib.request
import urllib.error
import ssl
from pathlib import Path
from datetime import datetime, timezone

SOURCES_FILE = Path(__file__).parent.parent / "skills" / "trend-scouting" / "sources.json"

# Skip SSL verification for simplicity
CTX = ssl.create_default_context()
CTX.check_hostname = False
CTX.verify_mode = ssl.CERT_NONE

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}


def check_url(url: str, timeout: int = 15) -> dict:
    """Check if a URL is reachable. Returns status info."""
    start = time.time()
    try:
        req = urllib.request.Request(url, headers=HEADERS)
        resp = urllib.request.urlopen(req, timeout=timeout, context=CTX)
        elapsed = round(time.time() - start, 2)
        return {
            "reachable": True,
            "status_code": resp.getcode(),
            "response_time_s": elapsed,
            "content_type": resp.headers.get("Content-Type", ""),
        }
    except urllib.error.HTTPError as e:
        elapsed = round(time.time() - start, 2)
        return {
            "reachable": False,
            "status_code": e.code,
            "response_time_s": elapsed,
            "error": str(e.reason),
        }
    except Exception as e:
        elapsed = round(time.time() - start, 2)
        return {
            "reachable": False,
            "status_code": None,
            "response_time_s": elapsed,
            "error": str(e),
        }


def main():
    if not SOURCES_FILE.exists():
        print(f"ERROR: {SOURCES_FILE} not found")
        sys.exit(1)

    sources = json.loads(SOURCES_FILE.read_text())["sources"]
    now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    print(f"🔍 CE Source Health Check — {now}")
    print("=" * 70)

    results = []
    for src in sources:
        name = src["name"]
        # Check main URL
        main_result = check_url(src["url"])
        # Check RSS if available
        rss_result = None
        if src.get("rss_url"):
            rss_result = check_url(src["rss_url"])

        status_icon = "✅" if main_result["reachable"] else "❌"
        rss_icon = ""
        if rss_result:
            rss_icon = " | RSS: " + ("✅" if rss_result["reachable"] else "❌")

        line = f"{status_icon} {name:<30} {str(main_result.get('status_code', '---')):>4}  {main_result['response_time_s']:.1f}s{rss_icon}"
        if not main_result["reachable"]:
            line += f"  ⚠ {main_result.get('error', 'unknown')}"
        print(line)

        results.append({
            "name": name,
            "url": src["url"],
            "main": main_result,
            "rss": rss_result,
            "configured_status": src["status"],
        })

    print("=" * 70)

    # Summary
    working = sum(1 for r in results if r["main"]["reachable"])
    broken = len(results) - working
    print(f"\n📊 {working} reachable / {broken} unreachable / {len(results)} total")

    # Flag mismatches
    for r in results:
        if r["configured_status"] == "working" and not r["main"]["reachable"]:
            print(f"⚠️  DEGRADED: {r['name']} — configured as 'working' but unreachable!")
        if r["configured_status"] == "broken" and r["main"]["reachable"]:
            print(f"🔄 RECOVERED: {r['name']} — configured as 'broken' but now reachable!")


if __name__ == "__main__":
    main()
