#!/usr/bin/env python3
"""TEST_OPS — Capture panel 13 personnes via API locale."""
import json
import urllib.request
import time
import sys

PANEL = [
    "Khelil Ben Osman",
    "Pascal Herard",
    "Gil Charpenet",
    "Marie Le Boiteux",
    "Sylvie Leboiteux",
    "Olivier Iteanu",
    "Fabrice Epelboin",
    "Olivier Laurelli",
    "Herve Bokobza",
    "Emmanuel Macron",
    "Antoine Champagne",
    "Adrien Chapon",
    "Joachim Herard",
]

API_URL = "http://localhost:7777/api/query"


def capture_one(name):
    payload = json.dumps({"query": name, "lang": "fr"}).encode("utf-8")
    req = urllib.request.Request(
        API_URL,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    start = time.time()
    resp = urllib.request.urlopen(req, timeout=120)
    elapsed = round(time.time() - start, 1)
    data = json.loads(resp.read().decode("utf-8"))
    r = data.get("result", {})

    # Portrait = images[0] si present
    imgs = r.get("images", [])
    portrait_url = imgs[0].get("url", "") if imgs else ""
    portrait_source = imgs[0].get("source", "") if imgs else ""

    # Sources = liste des domaines
    sources = r.get("sources_used", [])
    source_domains = [s.get("domain", "") for s in sources]

    # Publications
    pubs = r.get("publications", {})
    pub_titles = []
    if isinstance(pubs, dict):
        feat = pubs.get("featured")
        if feat and isinstance(feat, dict):
            pub_titles.append(feat.get("title", ""))
        for o in pubs.get("others", []) or []:
            if isinstance(o, dict):
                pub_titles.append(o.get("title", ""))
    elif isinstance(pubs, list):
        for p in pubs:
            if isinstance(p, dict):
                pub_titles.append(p.get("title", ""))

    summary = r.get("summary", "")
    age_mentioned = "age" in summary.lower() or " ans" in summary.lower()

    return {
        "synthese": summary,
        "synthese_chars": len(summary),
        "sources": source_domains,
        "sources_count": len(source_domains),
        "portrait_url": portrait_url,
        "portrait_source": portrait_source,
        "publications": pub_titles,
        "age_mentioned": age_mentioned,
        "cached": r.get("cached", False),
        "content_type": r.get("content_type", ""),
        "elapsed_s": elapsed,
    }


def main():
    label = sys.argv[1] if len(sys.argv) > 1 else "CAPTURE"
    output_file = sys.argv[2] if len(sys.argv) > 2 else "results.json"
    results = {}
    for i, name in enumerate(PANEL):
        tag = "[" + label + "] " + str(i + 1) + "/13"
        print(tag + " -- " + name + "...", flush=True)
        try:
            cap = capture_one(name)
            results[name] = cap
            msg = (
                "  OK: " + str(cap["synthese_chars"]) + " chars, "
                + str(cap["sources_count"]) + " sources, "
                + "portrait=" + ("OUI" if cap["portrait_url"] else "NON")
                + ", cached=" + str(cap["cached"])
                + ", " + str(cap["elapsed_s"]) + "s"
            )
            print(msg, flush=True)
        except Exception as e:
            results[name] = {"error": str(e)}
            print("  ERREUR: " + str(e), flush=True)
        if i < len(PANEL) - 1:
            time.sleep(2)

    with open(output_file, "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=2)
    print("\n[" + label + "] Resultats sauvegardes dans " + output_file)


if __name__ == "__main__":
    main()
