"""CLI for A2RAG package: a2rag dashboard / a2rag metrics / a2rag export"""
import sys, os

def main():
    args = sys.argv[1:]
    if not args or args[0] == "help":
        print("""
A2RAG CLI

Commands:
  a2rag dashboard          Launch local analytics dashboard
  a2rag metrics            Print metrics summary
  a2rag export <path>      Export decisions to CSV
  a2rag clear [days]       Clear decisions older than N days (default: 90)

Environment:
  A2RAG_API_KEY            Your API key (or pass --key)
""")
        return

    api_key = os.environ.get("A2RAG_API_KEY", "")
    if not api_key:
        print("Error: set A2RAG_API_KEY environment variable")
        sys.exit(1)

    from a2rag import A2RAGClient
    client = A2RAGClient(api_key=api_key)

    cmd = args[0]

    if cmd == "dashboard":
        port = int(args[1]) if len(args) > 1 else 7860
        client.dashboard(port=port)

    elif cmd == "metrics":
        days = int(args[1]) if len(args) > 1 else 30
        m = client.metrics(days=days)
        print(f"\n  A2RAG Metrics (last {days} days)")
        print(f"  {'─'*40}")
        print(f"  Total decisions:    {m.total}")
        print(f"  Answer rate:        {m.answer_rate:.1%}")
        print(f"  Clarify rate:       {m.clarify_rate:.1%}")
        print(f"  Abstain rate:       {m.abstain_rate:.1%}")
        print(f"  UAR:                {m.uar:.1%}  (lower is better)")
        print(f"  ORS:                {m.ors:.1%}  (overall reliability)")
        print(f"  Avg latency:        {m.avg_latency_ms:.0f}ms")
        print(f"  Avg confidence:     {m.avg_confidence:.1%}")
        print()

    elif cmd == "export":
        path = args[1] if len(args) > 1 else "a2rag_decisions.csv"
        out = client.export(path)
        print(f"  Exported to {out}")

    elif cmd == "clear":
        days = int(args[1]) if len(args) > 1 else 90
        n = client.clear_local_data(older_than_days=days)
        print(f"  Deleted {n} decisions older than {days} days")

    else:
        print(f"Unknown command: {cmd}. Run 'a2rag help'")
