"""
Live end-to-end smoke test.

    python tests/smoke.py            # engine, in-process
    python tests/smoke.py --api      # against a running server on :8000
"""
from __future__ import annotations

import asyncio
import json
import logging
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

logging.disable(logging.WARNING)

from deepsearch.core import close_client  # noqa: E402
from deepsearch.engine import engine, health  # noqa: E402
from deepsearch.schemas import SearchRequest  # noqa: E402

CASES = [
    ("what is the current RBI repo rate", "instant"),
    ("difference between asyncio.gather and TaskGroup in Python", "fast"),
    ("how does retrieval augmented generation reduce hallucinations", "deep"),
]


def ok(label: str, cond: bool, detail: str = "") -> bool:
    print(f"  {'✅' if cond else '❌'} {label}{(' — ' + detail) if detail else ''}")
    return cond


async def main() -> int:
    passed = True

    print("\n── health ─────────────────────────────────────────────")
    h = health()
    passed &= ok(f"{len(h['providers']['active'])} providers registered",
                 len(h["providers"]["active"]) >= 10)
    passed &= ok("synthesis layer reachable", h["llm_available"])

    for query, depth in CASES:
        print(f"\n── {depth.upper()}: {query[:52]} ──")
        t0 = time.perf_counter()
        res = await engine.search(SearchRequest(query=query, depth=depth,
                                                max_results=8, cache=False))
        el = time.perf_counter() - t0
        st, ps = res.stats, res.provider_stats

        passed &= ok(f"{el:.1f}s elapsed", el < 120)
        passed &= ok(f"{ps.get('live_providers', 0)} live providers",
                     ps.get("live_providers", 0) >= 2)
        passed &= ok(f"{st.get('candidates_found', 0)} candidates found",
                     st.get("candidates_found", 0) >= 5)
        passed &= ok(f"{len(res.sources)} sources returned", len(res.sources) >= 3)
        passed &= ok(f"{st.get('unique_domains', 0)} unique domains",
                     st.get("unique_domains", 0) >= 2)
        passed &= ok(f"answer generated ({len(res.answer)} chars)",
                     len(res.answer) > 80)
        passed &= ok("answer contains citations", "[" in res.answer)
        if depth != "instant":
            passed &= ok(f"{st.get('pages_read', 0)} pages read "
                         f"({st.get('words_read', 0):,} words)",
                         st.get("pages_read", 0) >= 1)
        print(f"\n  {res.answer[:260].strip()}…\n")
        for s in res.sources[:4]:
            print(f"    [{s.id}] {s.domain:26s} {s.title[:44]}")

    print("\n── caching ────────────────────────────────────────────")
    q = SearchRequest(query="what is quantum entanglement", depth="instant")
    t0 = time.perf_counter()
    await engine.search(q)
    cold = time.perf_counter() - t0
    t0 = time.perf_counter()
    r2 = await engine.search(q)
    warm = time.perf_counter() - t0
    passed &= ok(f"cache hit {cold:.2f}s → {warm:.3f}s", r2.cached and warm < cold)

    await close_client()
    print("\n" + ("🎉 ALL CHECKS PASSED" if passed else "⚠️  SOME CHECKS FAILED") + "\n")
    return 0 if passed else 1


if __name__ == "__main__":
    raise SystemExit(asyncio.run(main()))
