"""
CLI Commands for AI Knowledge Plugin

Provides command-line interface for knowledge management operations.
Designed to work with Claude Code's command system.
"""

import sys
import argparse
from pathlib import Path
from typing import Optional, List

from ..core.exporter import export_knowledge_pack, export_to_directory, get_export_preview
from ..core.importer import import_knowledge_pack
from ..core.knowledge_manager import KnowledgeManager
from .server_manager import start_server, stop_server, get_status


def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        description="ThinkBank Knowledge Management CLI",
        prog="thinkbank"
    )

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

    # Hub command
    hub_parser = subparsers.add_parser('hub', help='Start web UI')
    hub_parser.add_argument('--port', type=int, default=8765, help='Port number (default: 8765)')
    hub_parser.add_argument('--no-browser', action='store_true', help='Do not open browser')

    # Stop command
    subparsers.add_parser('stop', help='Stop web UI')

    # Status command
    subparsers.add_parser('status', help='Check server status')

    # Export command
    export_parser = subparsers.add_parser('export', help='Export knowledge pack')
    export_parser.add_argument('output', help='Output file path (.khb)')
    export_parser.add_argument('--type', help='Filter by knowledge type')
    export_parser.add_argument('--min-score', type=float, help='Minimum score threshold')
    export_parser.add_argument('--tags', help='Filter by tags (comma-separated)')
    export_parser.add_argument('--limit', type=int, help='Maximum number of items')
    export_parser.add_argument('--name', help='Pack name')
    export_parser.add_argument('--author', help='Author name')
    export_parser.add_argument('--description', help='Pack description')
    export_parser.add_argument('--format', choices=['json', 'yaml'], default='json', help='Export format')
    export_parser.add_argument('--preview', action='store_true', help='Preview without exporting')

    # Import command
    import_parser = subparsers.add_parser('import', help='Import knowledge pack')
    import_parser.add_argument('pack_path', help='Path to .khb file')
    import_parser.add_argument('--conflict', choices=['skip', 'overwrite', 'merge', 'rename', 'ask'],
                                default='ask', help='Conflict resolution strategy')
    import_parser.add_argument('--dry-run', action='store_true', help='Preview without importing')

    # List command
    list_parser = subparsers.add_parser('list', help='List knowledge items')
    list_parser.add_argument('--type', help='Filter by knowledge type')
    list_parser.add_argument('--min-score', type=float, help='Minimum score threshold')
    list_parser.add_argument('--tags', help='Filter by tags (comma-separated)')
    list_parser.add_argument('--limit', type=int, default=20, help='Maximum number of items (default: 20)')

    # Search command
    search_parser = subparsers.add_parser('search', help='Search knowledge items')
    search_parser.add_argument('query', help='Search query')
    search_parser.add_argument('--type', help='Filter by knowledge type')

    args = parser.parse_args()

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

    # Route to appropriate handler
    if args.command == 'hub':
        return cmd_hub(args)
    elif args.command == 'stop':
        return cmd_stop(args)
    elif args.command == 'status':
        return cmd_status(args)
    elif args.command == 'export':
        return cmd_export(args)
    elif args.command == 'import':
        return cmd_import(args)
    elif args.command == 'list':
        return cmd_list(args)
    elif args.command == 'search':
        return cmd_search(args)
    else:
        parser.print_help()
        return 1


def cmd_hub(args) -> int:
    """Handle 'hub' command."""
    result = start_server(
        port=args.port,
        open_browser=not args.no_browser
    )
    return 0 if result['success'] else 1


def cmd_stop(args) -> int:
    """Handle 'stop' command."""
    result = stop_server()
    return 0 if result['success'] else 1


def cmd_status(args) -> int:
    """Handle 'status' command."""
    get_status()
    return 0


def cmd_export(args) -> int:
    """Handle 'export' command."""
    # Build filter criteria
    filter_criteria = {}
    if args.type:
        filter_criteria['type'] = args.type
    if args.min_score:
        filter_criteria['min_score'] = args.min_score
    if args.tags:
        filter_criteria['tags'] = [t.strip() for t in args.tags.split(',')]
    if args.limit:
        filter_criteria['limit'] = args.limit

    # Build metadata
    metadata = {}
    if args.name:
        metadata['name'] = args.name
    if args.author:
        metadata['author'] = args.author
    if args.description:
        metadata['description'] = args.description

    # Preview mode
    if args.preview:
        preview = get_export_preview(filter_criteria)
        print(f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📦 Export Preview

Total Items: {preview['count']}
Estimated Size: {preview['estimated_size_kb']} KB

Type Breakdown:
{_format_type_counts(preview['type_counts'])}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        """)
        return 0

    # Actual export
    print(f"⏳ Exporting knowledge...")
    result = export_knowledge_pack(
        output_path=args.output,
        filter_criteria=filter_criteria if filter_criteria else None,
        format=args.format,
        metadata=metadata if metadata else None
    )

    if result['success']:
        print(f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ Export Complete

Items: {result['count']}
File: {result['path']}
Size: {result['size_kb']} KB

Metadata:
  Name: {result['metadata']['name']}
  Author: {result['metadata']['author']}
  Created: {result['metadata']['created']}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        """)
        return 0
    else:
        print(f"✗ Export failed: {result.get('error', 'Unknown error')}")
        return 1


def cmd_import(args) -> int:
    """Handle 'import' command."""
    print(f"⏳ Importing knowledge pack...")

    result = import_knowledge_pack(
        pack_path=args.pack_path,
        conflict_resolution=args.conflict,
        dry_run=args.dry_run
    )

    if not result['success']:
        print(f"✗ Import failed: {result.get('error', 'Unknown error')}")
        return 1

    # Display summary
    print(f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
{"📋 Import Preview (Dry Run)" if result['dry_run'] else "✓ Import Complete"}

Pack: {result['pack_metadata']['name']}
Author: {result['pack_metadata']['author']}

Results:
  Total Items: {result['total_items']}
  Imported: {result['imported_count']}
  Skipped: {result['skipped_count']}
  Conflicts: {result['conflict_count']}
  Errors: {result['error_count']}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    """)

    # Show conflicts if any
    if result['conflicts']:
        print("⚠ Conflicts requiring resolution:")
        for conflict in result['conflicts'][:5]:  # Show first 5
            print(f"  - {conflict['title']} (ID: {conflict['id']})")
            print(f"    Existing score: {conflict['existing_score']:.2f}")
            print(f"    New score: {conflict['new_score']:.2f}")
        if len(result['conflicts']) > 5:
            print(f"  ... and {len(result['conflicts']) - 5} more")
        print("\nRe-run with --conflict option to resolve automatically.")

    # Show errors if any
    if result['errors']:
        print("\n✗ Errors:")
        for error in result['errors'][:5]:
            print(f"  - {error['title']}: {error['error']}")
        if len(result['errors']) > 5:
            print(f"  ... and {len(result['errors']) - 5} more")

    return 0


def cmd_list(args) -> int:
    """Handle 'list' command."""
    km = KnowledgeManager()

    # Build filters
    tags = [t.strip() for t in args.tags.split(',')] if args.tags else None

    items = km.list(
        knowledge_type=args.type,
        min_score=args.min_score,
        tags=tags,
        limit=args.limit
    )

    if not items:
        print("No knowledge items found.")
        return 0

    print(f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📚 Knowledge Items ({len(items)} found)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    """)

    for item in items:
        fm = item['frontmatter']
        print(f"""
{fm.get('type', 'unknown').upper()}: {fm.get('title', 'Untitled')}
ID: {fm.get('id', 'unknown')}
Score: {fm.get('score', 0.0):.2f}
Tags: {', '.join(fm.get('tags', []))}
        """.strip())
        print()

    return 0


def cmd_search(args) -> int:
    """Handle 'search' command."""
    km = KnowledgeManager()

    items = km.search(
        query=args.query,
        knowledge_type=args.type,
        search_content=True
    )

    if not items:
        print(f"No results found for: {args.query}")
        return 0

    print(f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 Search Results for "{args.query}" ({len(items)} found)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    """)

    for item in items[:10]:  # Show first 10 results
        fm = item['frontmatter']
        match_type = item.get('match_type', 'unknown')
        print(f"""
{fm.get('type', 'unknown').upper()}: {fm.get('title', 'Untitled')}
ID: {fm.get('id', 'unknown')}
Score: {fm.get('score', 0.0):.2f}
Match: {match_type}
        """.strip())
        print()

    if len(items) > 10:
        print(f"... and {len(items) - 10} more results")

    return 0


def _format_type_counts(type_counts: dict) -> str:
    """Format type counts for display."""
    lines = []
    for ktype, count in sorted(type_counts.items()):
        lines.append(f"  {ktype}: {count}")
    return '\n'.join(lines) if lines else "  (none)"


if __name__ == '__main__':
    sys.exit(main())
