"""MemoTrail CLI — index history and run MCP server."""

import argparse
import sys

from memotrail.utils import get_logger

logger = get_logger("memotrail.cli")


def cmd_serve(args):
    """Run the MCP server."""
    from memotrail.server import main as server_main
    server_main()


def cmd_index(args):
    """Index conversation history from supported platforms."""
    from memotrail.collectors import COLLECTORS
    from memotrail.core.indexer import Indexer

    source = getattr(args, "source", None)
    index_all = getattr(args, "all", False)

    if source:
        sources = [source] if source in COLLECTORS else []
        if not sources:
            print(f"Unknown source: {source}")
            print(f"Available sources: {', '.join(COLLECTORS.keys())}")
            return
    elif index_all:
        sources = list(COLLECTORS.keys())
    else:
        sources = ["claude_code"]

    indexer = Indexer()
    sqlite = indexer.sqlite
    total_indexed = 0
    total_skipped = 0
    total_messages = 0

    for source_name in sources:
        collector = COLLECTORS[source_name]
        print(f"\nIndexing {source_name}...")

        try:
            files = collector.find_session_files()
        except Exception as e:
            print(f"  ✗ Error finding {source_name} files: {e}")
            continue

        if not files:
            print(f"  No {source_name} sessions found.")
            continue

        for f in files:
            file_path = str(f)
            if sqlite.is_file_indexed(file_path):
                total_skipped += 1
                continue

            try:
                result = collector.parse_session_file(f)
                sessions = result if isinstance(result, list) else [result]

                last_session_id = None
                for parsed in sessions:
                    if not parsed.get("messages"):
                        continue
                    session_id = indexer.index_session(
                        messages=parsed["messages"],
                        project=parsed.get("project"),
                        source=source_name,
                    )
                    last_session_id = session_id
                    total_indexed += 1
                    total_messages += len(parsed["messages"])
                    print(f"  ✓ Indexed: {parsed.get('project') or 'unknown'} "
                          f"({len(parsed['messages'])} messages)")

                if last_session_id:
                    sqlite.mark_file_indexed(file_path, last_session_id)
            except Exception as e:
                logger.error(f"Failed to index session: {e}")
                print(f"  ✗ Failed: {f} — {e}")

    print(f"\nDone! Indexed {total_indexed} new sessions ({total_messages} messages)")
    if total_skipped:
        print(f"  Skipped {total_skipped} already-indexed sessions")
    print("You can now use MemoTrail in Claude Code:")
    print("  claude mcp add memotrail -- memotrail serve")


def cmd_search(args):
    """Quick search from CLI."""
    from memotrail.core.searcher import Searcher

    searcher = Searcher()
    results = searcher.search_chats(args.query, limit=args.limit)

    if not results:
        print("No results found.")
        return

    for i, r in enumerate(results, 1):
        print(f"\n--- Result {i} (score: {r.score:.2f}) ---")
        print(f"Session: {r.session_id} | Project: {r.project or 'unknown'}")
        print(f"Time: {r.timestamp or 'unknown'}")
        print(r.chunk_text[:500])


def cmd_export(args):
    """Export MemoTrail data to JSON."""
    from memotrail.sync.exporter import DataExporter

    exporter = DataExporter()
    output = args.output
    project = getattr(args, "project", None)

    if project:
        summary = exporter.export_project(project, output)
        print(f"Exported project '{project}' to {output}")
    else:
        summary = exporter.export_all(output)
        print(f"Exported all data to {output}")

    for key, count in summary.items():
        print(f"  {key}: {count}")


def cmd_import(args):
    """Import MemoTrail data from JSON."""
    from memotrail.sync.importer import DataImporter

    importer = DataImporter()
    counts = importer.import_from_file(args.input)

    print(f"Imported from {args.input}:")
    for key, count in counts.items():
        print(f"  {key}: {count}")


def cmd_migrate(args):
    """Run database migrations."""
    from memotrail.storage import SQLiteStore
    from memotrail.storage.migrations import Migrator

    sqlite = SQLiteStore()
    migrator = Migrator(sqlite.conn)

    current = migrator.get_current_version()
    target = migrator.get_target_version()

    print(f"Current schema version: {current}")
    print(f"Target schema version: {target}")

    if current >= target:
        print("Database is up to date.")
        return

    applied = migrator.migrate()
    if applied:
        print(f"Applied {len(applied)} migration(s): {applied}")
    else:
        print("No migrations to apply.")


def cmd_dashboard(args):
    """Launch the web dashboard."""
    try:
        import uvicorn
    except ImportError:
        print("Dashboard requires extra dependencies. Install with:")
        print("  pip install memotrail[web]")
        return

    host = args.host
    port = args.port
    print(f"Starting MemoTrail Dashboard at http://{host}:{port}")
    uvicorn.run("memotrail.web.app:app", host=host, port=port, reload=False)


def cmd_stats(args):
    """Show MemoTrail statistics."""
    from memotrail.storage import SQLiteStore, ChromaStore

    sqlite = SQLiteStore()
    chroma = ChromaStore()

    db_stats = sqlite.get_stats()
    chat_chunks = chroma.get_collection_count(ChromaStore.CHAT_COLLECTION)
    memory_chunks = chroma.get_collection_count(ChromaStore.MEMORY_COLLECTION)

    print("MemoTrail Stats")
    print("=" * 30)
    print(f"Sessions indexed:     {db_stats['total_sessions']}")
    print(f"Messages stored:      {db_stats['total_messages']}")
    print(f"Decisions recorded:   {db_stats['total_decisions']}")
    print(f"Chat chunks:          {chat_chunks}")
    print(f"Memory notes:         {memory_chunks}")


def main():
    parser = argparse.ArgumentParser(
        prog="memotrail",
        description="MemoTrail — Persistent memory for AI coding assistants",
    )
    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # serve
    serve_parser = subparsers.add_parser("serve", help="Run MCP server")

    # index
    index_parser = subparsers.add_parser("index", help="Index conversation history")
    index_parser.add_argument("--source", choices=["claude_code", "cursor", "copilot", "windsurf", "aider"],
                              help="Index a specific source")
    index_parser.add_argument("--all", action="store_true", help="Index all sources")

    # search
    search_parser = subparsers.add_parser("search", help="Search conversations")
    search_parser.add_argument("query", help="Search query")
    search_parser.add_argument("-n", "--limit", type=int, default=5, help="Max results")

    # export
    export_parser = subparsers.add_parser("export", help="Export data to JSON")
    export_parser.add_argument("output", help="Output JSON file path")
    export_parser.add_argument("--project", help="Export only a specific project")

    # import
    import_parser = subparsers.add_parser("import", help="Import data from JSON")
    import_parser.add_argument("input", help="Input JSON file path")

    # migrate
    migrate_parser = subparsers.add_parser("migrate", help="Run database migrations")

    # dashboard
    dashboard_parser = subparsers.add_parser("dashboard", help="Launch web dashboard")
    dashboard_parser.add_argument("--host", default="127.0.0.1", help="Host (default: 127.0.0.1)")
    dashboard_parser.add_argument("--port", type=int, default=8765, help="Port (default: 8765)")

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

    args = parser.parse_args()

    if args.command == "serve":
        cmd_serve(args)
    elif args.command == "index":
        cmd_index(args)
    elif args.command == "search":
        cmd_search(args)
    elif args.command == "export":
        cmd_export(args)
    elif args.command == "import":
        cmd_import(args)
    elif args.command == "migrate":
        cmd_migrate(args)
    elif args.command == "dashboard":
        cmd_dashboard(args)
    elif args.command == "stats":
        cmd_stats(args)
    else:
        parser.print_help()
        sys.exit(1)


if __name__ == "__main__":
    main()
