"""
cogniq CLI — use from terminal.

  cogniq add "your text here"
  cogniq add --file document.txt
  cogniq ask "your question"
  cogniq search "keyword"
  cogniq info
"""

import argparse
import sys
import os
import pickle
from pathlib import Path

STATE_FILE = Path.home() / ".cogniq" / "state.pkl"


def load_rag():
    from cogniq import RAG
    if STATE_FILE.exists():
        try:
            return RAG.load(STATE_FILE)
        except Exception:
            pass
    return RAG()


def save_rag(rag):
    STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
    rag.save(STATE_FILE)


def cmd_add(args):
    rag = load_rag()
    if args.file:
        path = Path(args.file)
        if not path.exists():
            print(f"File not found: {args.file}", file=sys.stderr)
            sys.exit(1)
        rag.add(path, source=path.name)
        print(f"✓ Added file: {args.file} ({len(rag)} total docs)")
    elif args.text:
        rag.add(args.text)
        print(f"✓ Added text ({len(rag)} total docs)")
    else:
        print("Provide --text or --file", file=sys.stderr)
        sys.exit(1)
    save_rag(rag)


def cmd_ask(args):
    rag = load_rag()
    result = rag.ask(args.question, top_k=args.top_k)
    if args.show_sources:
        result.show()
    else:
        print(result.answer)
        print(f"\n⏱  {result.latency_ms:.1f}ms | {len(result.sources)} sources")


def cmd_search(args):
    rag = load_rag()
    results = rag.search(args.query, top_k=args.top_k)
    for i, r in enumerate(results, 1):
        print(f"\n[{i}] score={r.score:.3f} | {r.source}")
        print(f"    {r.text[:200]}...")


def cmd_info(args):
    rag = load_rag()
    info = rag.info()
    print(f"\nCogniQ RAG Status")
    print(f"{'─'*40}")
    for k, v in info.items():
        print(f"  {k:20s}: {v}")


def cmd_reset(args):
    if STATE_FILE.exists():
        STATE_FILE.unlink()
    print("✓ Reset complete")


def main():
    parser = argparse.ArgumentParser(
        prog="cogniq",
        description="CogniQ — Next-gen hybrid RAG from the command line",
    )
    sub = parser.add_subparsers(dest="command")

    # add
    p_add = sub.add_parser("add", help="Add a document")
    p_add.add_argument("text", nargs="?", help="Text to add")
    p_add.add_argument("--file", "-f", help="File path to add")

    # ask
    p_ask = sub.add_parser("ask", help="Ask a question")
    p_ask.add_argument("question")
    p_ask.add_argument("--top-k", "-k", type=int, default=5)
    p_ask.add_argument("--sources", "-s", dest="show_sources", action="store_true")

    # search
    p_srch = sub.add_parser("search", help="Semantic search")
    p_srch.add_argument("query")
    p_srch.add_argument("--top-k", "-k", type=int, default=5)

    # info
    sub.add_parser("info", help="Show RAG info")

    # reset
    sub.add_parser("reset", help="Clear all documents")

    args = parser.parse_args()

    dispatch = {
        "add": cmd_add,
        "ask": cmd_ask,
        "search": cmd_search,
        "info": cmd_info,
        "reset": cmd_reset,
    }

    fn = dispatch.get(args.command)
    if fn:
        fn(args)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
