"""SeevoMap CLI — command-line interface for the AI Research Knowledge Graph."""

import argparse
import json
import sys

from seevomap.client import SeevoMap, SeevoMapError
from seevomap import formatter


def main():
    parser = argparse.ArgumentParser(
        prog="seevomap",
        description="SeevoMap — AI Research Knowledge Graph (BotResearchNet)",
    )
    parser.add_argument(
        "--endpoint", default=None,
        help="Custom SeevoMap Space URL (default: HuggingFace Space)",
    )

    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # search
    p_search = subparsers.add_parser("search", help="Search related research experiences")
    p_search.add_argument("query", help="Task description to search for")
    p_search.add_argument("--top-k", type=int, default=10, help="Number of results (default: 10)")

    # inject
    p_inject = subparsers.add_parser("inject", help="Get formatted prompt context for agent injection")
    p_inject.add_argument("query", help="Task description")
    p_inject.add_argument("--top-k", type=int, default=10, help="Number of results (default: 10)")

    # get
    p_get = subparsers.add_parser("get", help="Get node details or map data")
    get_sub = p_get.add_subparsers(dest="get_type")
    p_get_node = get_sub.add_parser("node", help="Get a single node by ID")
    p_get_node.add_argument("node_id", help="Node ID")
    p_get_map = get_sub.add_parser("map", help="Download map.json")
    p_get_map.add_argument("-o", "--output", default="map.json", help="Output file (default: map.json)")

    # stats
    subparsers.add_parser("stats", help="Show graph statistics")

    # submit
    p_submit = subparsers.add_parser("submit", help="Submit experiment results to the graph")
    p_submit.add_argument("file", nargs="?", help="JSON file with node data")
    p_submit.add_argument("--dir", help="Directory of JSON files to batch submit")

    # review (maintainer)
    p_review = subparsers.add_parser("review", help="Review pending nodes (maintainer)")
    p_review.add_argument("--pending", action="store_true", help="List pending nodes")
    p_review.add_argument("--approve", metavar="ID", help="Approve a node")
    p_review.add_argument("--reject", metavar="ID", help="Reject a node")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        sys.exit(0)

    svm = SeevoMap(endpoint=args.endpoint)

    try:
        if args.command == "search":
            results = svm.search(args.query, top_k=args.top_k)
            formatter.print_search_results(results)

        elif args.command == "inject":
            text = svm.inject(args.query, top_k=args.top_k)
            formatter.print_inject(text)

        elif args.command == "get":
            if args.get_type == "node":
                node = svm.get_node(args.node_id)
                formatter.print_node(node)
            elif args.get_type == "map":
                # Download map data - for now just note it's available on HF
                print(f"Map data available at: https://huggingface.co/datasets/akiwatanabe/seevomap-graph/resolve/main/map.json")
                print(f"Download: curl -L -o {args.output} https://huggingface.co/datasets/akiwatanabe/seevomap-graph/resolve/main/map.json")
            else:
                print("Usage: seevomap get node <id> | seevomap get map [-o file]")

        elif args.command == "stats":
            stats = svm.stats()
            formatter.print_stats(stats)

        elif args.command == "submit":
            if args.dir:
                import pathlib
                files = sorted(pathlib.Path(args.dir).glob("*.json"))
                if not files:
                    print(f"No JSON files found in {args.dir}")
                    sys.exit(1)
                for f in files:
                    with open(f, "r", encoding="utf-8") as fh:
                        node = json.load(fh)
                    result = svm.submit(node)
                    print(f"{f.name}: ", end="")
                    formatter.print_submit_result(result)
            elif args.file:
                with open(args.file, "r", encoding="utf-8") as f:
                    node = json.load(f)
                result = svm.submit(node)
                formatter.print_submit_result(result)
            else:
                print("Usage: seevomap submit <file.json> | seevomap submit --dir <directory>")
                sys.exit(1)

        elif args.command == "review":
            if args.pending:
                pending = svm.list_pending()
                formatter.print_pending(pending)
            elif args.approve:
                result = svm.review(args.approve, "approve")
                formatter.print_review_result(result)
            elif args.reject:
                result = svm.review(args.reject, "reject")
                formatter.print_review_result(result)
            else:
                print("Usage: seevomap review --pending | --approve <id> | --reject <id>")

    except SeevoMapError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)
    except KeyboardInterrupt:
        sys.exit(130)


if __name__ == "__main__":
    main()
