"""
DeepSearch CLI.

    python -m deepsearch.cli "your question" --depth deep
    python -m deepsearch.cli "your question" --json > out.json
"""
from __future__ import annotations

import argparse
import asyncio
import json
import logging
import sys
import time

from .core import close_client
from .engine import engine
from .schemas import SearchRequest

C = {
    "b": "\033[1m", "d": "\033[2m", "r": "\033[0m", "cy": "\033[36m",
    "gr": "\033[32m", "yl": "\033[33m", "bl": "\033[34m", "mg": "\033[35m",
}


def _c(text: str, *styles: str) -> str:
    if not sys.stdout.isatty():
        return text
    return "".join(C[s] for s in styles) + text + C["r"]


async def _run(args: argparse.Namespace) -> int:
    req = SearchRequest(
        query=args.query, depth=args.depth, max_results=args.max_results,
        answer=not args.no_answer, freshness=args.freshness,
        language=args.language,
        include_domains=[d for d in (args.include or "").split(",") if d],
        exclude_domains=[d for d in (args.exclude or "").split(",") if d],
        providers=[p for p in (args.providers or "").split(",") if p],
    )
    t0 = time.perf_counter()
    if not args.json:
        print(_c(f"\n🔍 {args.query}", "b"))
        print(_c(f"   depth={args.depth} · searching…\n", "d"))
    res = await engine.search(req)
    await close_client()

    if args.json:
        print(json.dumps(res.model_dump(), indent=2, ensure_ascii=False))
        return 0

    if res.sub_queries and len(res.sub_queries) > 1:
        print(_c("SEARCH ANGLES", "b", "mg"))
        for q in res.sub_queries:
            print(f"  {_c('▸', 'mg')} {q}")
        print()

    if res.answer:
        print(_c("ANSWER", "b", "cy"))
        print(res.answer)
        print()

    if res.key_points:
        print(_c("KEY POINTS", "b", "gr"))
        for k in res.key_points:
            print(f"  {_c('•', 'gr')} {k}")
        print()

    print(_c(f"SOURCES ({len(res.sources)})", "b", "yl"))
    for s in res.sources:
        flag = _c(" ✓read", "gr") if s.read else ""
        print(f"  {_c(f'[{s.id}]', 'yl')} {s.title[:78]}{flag}")
        print(f"      {_c(s.url[:100], 'd')}")
    print()

    if res.follow_ups:
        print(_c("FOLLOW-UPS", "b", "bl"))
        for f in res.follow_ups:
            print(f"  {_c('?', 'bl')} {f}")
        print()

    st = res.stats
    ps = res.provider_stats
    print(_c(
        f"⚡ {time.perf_counter()-t0:.1f}s · {st.get('candidates_found',0)} candidates · "
        f"{st.get('pages_read',0)} pages read · {st.get('unique_domains',0)} domains · "
        f"{ps.get('live_providers',0)} live providers", "d"))
    return 0


def main() -> int:
    p = argparse.ArgumentParser(
        prog="deepsearch", description="Advanced multi-source AI web search")
    p.add_argument("query", help="your question")
    p.add_argument("-d", "--depth", default="fast",
                   choices=["instant", "fast", "deep", "extreme"])
    p.add_argument("-n", "--max-results", type=int, default=10)
    p.add_argument("-f", "--freshness", choices=["day", "week", "month", "year"])
    p.add_argument("-l", "--language", default="en")
    p.add_argument("--include", help="comma-separated domains to include")
    p.add_argument("--exclude", help="comma-separated domains to exclude")
    p.add_argument("--providers", help="comma-separated provider names")
    p.add_argument("--no-answer", action="store_true", help="retrieval only")
    p.add_argument("--json", action="store_true", help="raw JSON output")
    p.add_argument("-v", "--verbose", action="store_true")
    args = p.parse_args()

    logging.basicConfig(
        level=logging.INFO if args.verbose else logging.ERROR,
        format="%(levelname)s %(name)s: %(message)s",
    )
    if not args.verbose:
        logging.getLogger("httpx").setLevel(logging.CRITICAL)
    try:
        return asyncio.run(_run(args))
    except KeyboardInterrupt:
        print("\ninterrupted")
        return 130


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