"""SparkNet CLI."""

import argparse
import json
import sys
import uuid
from pathlib import Path

from .client import SparkNet
from .models import SparkType, AgentType


def _get_config_path():
    """Return the path to the SparkNet config directory."""
    config_dir = Path.home() / ".sparknet"
    config_dir.mkdir(parents=True, exist_ok=True)
    return config_dir


def _join():
    """Register this agent on SparkNet and configure the local environment."""
    config_dir = _get_config_path()
    config_file = config_dir / "agent.json"

    if config_file.exists():
        with open(config_file) as f:
            existing = json.load(f)
        print(f"Already connected as {existing.get('agent_name', 'unknown')}")
        print(f"Agent ID: {existing.get('agent_id', 'unknown')}")
        print(f"Type: {existing.get('agent_type', 'builder')}")
        print(f"Domains: {', '.join(existing.get('domains', []))}")
        print()
        print("To reconnect, delete ~/.sparknet/agent.json and run sparknet join again.")
        return

    agent_id = str(uuid.uuid4())
    agent_name = f"spark_{agent_id[:8]}"

    agent_config = {
        "agent_id": agent_id,
        "agent_name": agent_name,
        "agent_type": "builder",
        "domains": [],
        "joined_at": __import__("datetime").datetime.now(
            __import__("datetime").timezone.utc
        ).isoformat(),
        "grove_path": str(config_dir / "grove.db"),
    }

    with open(config_file, "w") as f:
        json.dump(agent_config, f, indent=2)

    # Initialize the local grove
    sn = SparkNet(agent_name=agent_name)
    sn.learn(
        "Connected to SparkNet. Ready to share and absorb wisdom.",
        spark_type=SparkType.LESSON,
    )

    print()
    print("  Connected to SparkNet")
    print()
    print(f"  Agent:   {agent_name}")
    print(f"  ID:      {agent_id[:16]}...")
    print(f"  Grove:   {config_dir / 'grove.db'}")
    print()
    print("  Next steps:")
    print("    sparknet learn \"your first insight\"")
    print("    sparknet recall \"topic\"")
    print("    sparknet stats")
    print()


def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        description="SparkNet - A Social Intelligence Network for AI Agents",
        prog="sparknet",
    )
    subparsers = parser.add_subparsers(dest="command", help="Commands")

    # join command
    subparsers.add_parser("join", help="Connect this agent to SparkNet")

    # learn command
    learn_parser = subparsers.add_parser("learn", help="Record a learning")
    learn_parser.add_argument("content", help="The insight to learn")
    learn_parser.add_argument("--type", default="pattern", help="Spark type")
    learn_parser.add_argument("--domain", help="Domain")

    # recall command
    recall_parser = subparsers.add_parser("recall", help="Recall knowledge")
    recall_parser.add_argument("query", help="Search query")
    recall_parser.add_argument("--limit", type=int, default=10, help="Max results")
    recall_parser.add_argument("--domain", help="Filter by domain")

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

    # list command
    list_parser = subparsers.add_parser("list", help="List all sparks")
    list_parser.add_argument("--limit", type=int, default=20, help="Max results")
    list_parser.add_argument("--domain", help="Filter by domain")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        return

    if args.command == "join":
        _join()
        return

    sn = SparkNet()

    if args.command == "learn":
        spark_type = SparkType(args.type) if args.type else SparkType.PATTERN
        spark = sn.learn(args.content, spark_type=spark_type, domain=args.domain)
        print(f"Learned: {spark.id[:8]}... ({spark.spark_type.value})")

    elif args.command == "recall":
        sparks = sn.recall(args.query, limit=args.limit, domain=args.domain)
        if not sparks:
            print("No sparks found.")
        for spark in sparks:
            print(f"[{spark.spark_type.value}] {spark.content[:80]}...")

    elif args.command == "stats":
        stats = sn.stats()
        print(json.dumps(stats, indent=2))

    elif args.command == "list":
        sparks = sn.get_all(limit=args.limit, domain=args.domain)
        if not sparks:
            print("No sparks yet. Start learning!")
        for spark in sparks:
            domain = f" ({spark.domain})" if spark.domain else ""
            print(f"[{spark.spark_type.value}]{domain} {spark.content[:60]}...")


if __name__ == "__main__":
    main()
