"""CLI runner for analyzers.

Usage:
    cd analysis-14022026
    python -m analyzers.runner --email user@example.com --since 2025-01-01 --until 2025-02-14
    python -m analyzers.runner --email user@example.com --since 2025-01-01 --until 2025-02-14 --analyzers a01,a02
    python -m analyzers.runner --email user@example.com --since 2025-01-01 --until 2025-02-14 --env prod
    python -m analyzers.runner --email user@example.com --since 2025-01-01 --until 2025-02-14 --include-llm
"""

import argparse
import json
import os
import importlib
import pkgutil

from .config import get_connection
from .base import load_session_data, BaseAnalyzer

# Modules that are not analyzers
_SKIP_MODULES = {"__init__", "config", "helpers", "base", "runner", "llm_cache"}


def discover_analyzers(include_llm: bool = False) -> list[BaseAnalyzer]:
    """Discover all analyzer modules in the analyzers package."""
    analyzers = []
    package_dir = os.path.dirname(os.path.abspath(__file__))

    for importer, modname, ispkg in pkgutil.iter_modules([package_dir]):
        if modname in _SKIP_MODULES:
            continue
        if not include_llm and modname.startswith("b"):
            continue
        try:
            mod = importlib.import_module(f".{modname}", package="analyzers")
            for attr_name in dir(mod):
                attr = getattr(mod, attr_name)
                if (isinstance(attr, type) and issubclass(attr, BaseAnalyzer)
                        and attr is not BaseAnalyzer):
                    analyzers.append(attr())
        except Exception as e:
            print(f"  [warning] Could not load analyzer {modname}: {e}")

    return analyzers


def main():
    parser = argparse.ArgumentParser(description="Run session analyzers")
    parser.add_argument("--email", required=True, help="User email to analyze")
    parser.add_argument("--since", required=True, help="Start date (YYYY-MM-DD)")
    parser.add_argument("--until", required=True, help="End date (YYYY-MM-DD)")
    parser.add_argument("--analyzers", default=None, help="Comma-separated analyzer names to run (default: all)")
    parser.add_argument("--env", default="local", choices=["local", "prod"], help="DB environment")
    parser.add_argument("--include-llm", action="store_true", help="Include LLM-based analyzers")
    args = parser.parse_args()

    # Connect and load data
    print(f"Connecting to {args.env} DB...")
    conn = get_connection(env=args.env)

    print(f"Loading data for {args.email} from {args.since} to {args.until}...")
    data = load_session_data(conn, args.email, args.since, args.until)
    conn.close()

    sessions_df = data["sessions"]
    messages_df = data["messages"]
    tool_calls_df = data["tool_calls"]
    tool_results_df = data["tool_results"]
    token_usage_df = data["token_usage"]

    print(f"  {len(sessions_df)} sessions found")
    print(f"  {len(messages_df)} messages")
    print(f"  {len(tool_calls_df)} tool calls")
    print(f"  {len(tool_results_df)} tool results")
    print(f"  {len(token_usage_df)} token usage rows")

    # Discover and filter analyzers
    all_analyzers = discover_analyzers(include_llm=args.include_llm)

    if args.analyzers:
        selected = set(args.analyzers.split(","))
        all_analyzers = [a for a in all_analyzers if a.name in selected]

    print(f"  {len(all_analyzers)} analyzers to run")

    # Run analyzers
    results = {}
    for analyzer in all_analyzers:
        print(f"  Running {analyzer.name}...")
        try:
            result = analyzer.analyze(sessions_df, messages_df, tool_calls_df, tool_results_df, token_usage_df)
            results[analyzer.name] = result
            print(f"    {analyzer.name} done")
        except Exception as e:
            print(f"    {analyzer.name} FAILED: {e}")
            import traceback
            traceback.print_exc()
            results[analyzer.name] = {"error": str(e)}

    # Write output
    safe_email = args.email.replace("@", "_at_").replace(".", "_")
    output_dir = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        "output", safe_email, f"{args.since}_to_{args.until}"
    )
    os.makedirs(output_dir, exist_ok=True)

    for name, result in results.items():
        path = os.path.join(output_dir, f"{name}.json")
        with open(path, "w") as f:
            json.dump(result, f, indent=2, default=str)

    # Combined output
    all_path = os.path.join(output_dir, "all.json")
    with open(all_path, "w") as f:
        json.dump(results, f, indent=2, default=str)

    print(f"\nSummary:")
    print(f"  Sessions: {len(sessions_df)}")
    print(f"  Analyzers run: {len(all_analyzers)}")
    print(f"  Output: {output_dir}")


if __name__ == "__main__":
    main()
