#!/usr/bin/env python3
"""
Command-line interface for managing artist lookup table.
Allows adding new artist variations and searching existing ones.
"""

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

# Add the src directory to the Python path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))

from src.utils.artist_lookup import artist_lookup, add_artist_fallback


def main():
    """Main CLI function for artist lookup table management."""
    parser = argparse.ArgumentParser(
        description="MusicBrainz Data Cleaner - Artist Lookup Table Manager",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
EXAMPLES:
  # Search for an artist in the lookup table
  python3 -m src.cli.artist_lookup_cli --search "Destiny's Child"
  
  # Add a new artist variation
  python3 -m src.cli.artist_lookup_cli --add "New Artist" --mbid "12345678-1234-1234-1234-123456789abc" --variations "Artist, The Artist, Artist Band"
  
  # List all artists in the lookup table
  python3 -m src.cli.artist_lookup_cli --list
  
  # Show statistics
  python3 -m src.cli.artist_lookup_cli --stats
        """
    )
    
    # Create subparsers for different commands
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Search command
    search_parser = subparsers.add_parser('search', help='Search for artists in lookup table')
    search_parser.add_argument('query', help='Artist name to search for')
    search_parser.add_argument('--min-score', type=float, default=0.6, 
                              help='Minimum fuzzy match score (0.0 to 1.0, default: 0.6)')
    
    # Add command
    add_parser = subparsers.add_parser('add', help='Add new artist variation to lookup table')
    add_parser.add_argument('--canonical-name', required=True, help='Canonical artist name')
    add_parser.add_argument('--mbid', required=True, help='MusicBrainz ID')
    add_parser.add_argument('--variations', required=True, 
                           help='Comma-separated list of name variations')
    add_parser.add_argument('--notes', default='', help='Optional notes about the artist')
    
    # List command
    list_parser = subparsers.add_parser('list', help='List all artists in lookup table')
    
    # Stats command
    stats_parser = subparsers.add_parser('stats', help='Show lookup table statistics')
    
    # Parse arguments
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
    
    # Execute commands
    if args.command == 'search':
        search_artists(args.query, args.min_score)
    elif args.command == 'add':
        add_artist(args.canonical_name, args.mbid, args.variations, args.notes)
    elif args.command == 'list':
        list_artists()
    elif args.command == 'stats':
        show_statistics()


def search_artists(query: str, min_score: float):
    """Search for artists in the lookup table."""
    print(f"🔍 Searching for '{query}' in artist lookup table...")
    print(f"📊 Minimum score: {min_score}")
    print("-" * 60)
    
    results = artist_lookup.search_artists(query, min_score)
    
    if not results:
        print("❌ No matches found")
        return
    
    print(f"✅ Found {len(results)} matches:")
    print()
    
    for i, result in enumerate(results, 1):
        print(f"{i}. {result['canonical_name']}")
        print(f"   MBID: {result['mbid']}")
        print(f"   Score: {result['score']:.2f}")
        print(f"   Match Type: {result['match_type']}")
        if result.get('matched_variation'):
            print(f"   Matched Variation: {result['matched_variation']}")
        if result.get('notes'):
            print(f"   Notes: {result['notes']}")
        print()


def add_artist(canonical_name: str, mbid: str, variations_str: str, notes: str):
    """Add a new artist variation to the lookup table."""
    print(f"➕ Adding artist variation to lookup table...")
    print(f"📝 Canonical Name: {canonical_name}")
    print(f"🆔 MBID: {mbid}")
    print(f"📋 Notes: {notes}")
    
    # Parse variations
    variations = [v.strip() for v in variations_str.split(',') if v.strip()]
    print(f"🔄 Variations: {', '.join(variations)}")
    print()
    
    # Add to lookup table
    success = add_artist_fallback(canonical_name, mbid, variations, notes)
    
    if success:
        print("✅ Artist variation added successfully!")
        
        # Show updated statistics
        stats = artist_lookup.get_statistics()
        print(f"📊 Updated statistics: {stats['total_artists']} artists, {stats['total_variations']} variations")
    else:
        print("❌ Failed to add artist variation")


def list_artists():
    """List all artists in the lookup table."""
    artists = artist_lookup.list_artists()
    
    if not artists:
        print("📚 Artist lookup table is empty")
        return
    
    print(f"📚 Found {len(artists)} artists in lookup table:")
    print("-" * 60)
    
    for i, artist in enumerate(sorted(artists), 1):
        print(f"{i}. {artist}")


def show_statistics():
    """Show lookup table statistics."""
    stats = artist_lookup.get_statistics()
    
    print("📊 Artist Lookup Table Statistics")
    print("=" * 40)
    print(f"Total Artists: {stats['total_artists']}")
    print(f"Total Variations: {stats['total_variations']}")
    
    if stats.get('metadata'):
        metadata = stats['metadata']
        print(f"Version: {metadata.get('version', 'Unknown')}")
        print(f"Last Updated: {metadata.get('last_updated', 'Unknown')}")
        print(f"Description: {metadata.get('description', 'No description')}")


if __name__ == "__main__":
    main() 