#!/usr/bin/env python3
"""
Script to reset karaoke tracking and re-download files with the new channel parser.

This script will:
1. Reset the karaoke_tracking.json to remove all downloaded entries
2. Optionally delete the downloaded files
3. Allow you to re-download with the new channel parser system
"""

import json
import os
import shutil
from pathlib import Path
from typing import List, Dict, Any


def reset_karaoke_tracking(tracking_file: str = "data/karaoke_tracking.json") -> None:
    """Reset the karaoke tracking file to empty state."""
    print(f"Resetting {tracking_file}...")
    
    # Create backup of current tracking
    backup_file = f"{tracking_file}.backup"
    if os.path.exists(tracking_file):
        shutil.copy2(tracking_file, backup_file)
        print(f"Created backup: {backup_file}")
    
    # Reset to empty state
    empty_tracking = {
        "playlists": {},
        "songs": {}
    }
    
    with open(tracking_file, 'w', encoding='utf-8') as f:
        json.dump(empty_tracking, f, indent=2, ensure_ascii=False)
    
    print(f"✅ Reset {tracking_file} to empty state")


def delete_downloaded_files(downloads_dir: str = "downloads") -> None:
    """Delete all downloaded files and folders."""
    if not os.path.exists(downloads_dir):
        print(f"Downloads directory {downloads_dir} does not exist.")
        return
    
    print(f"Deleting all files in {downloads_dir}...")
    
    try:
        shutil.rmtree(downloads_dir)
        print(f"✅ Deleted {downloads_dir} directory")
    except Exception as e:
        print(f"❌ Error deleting {downloads_dir}: {e}")


def show_download_stats(tracking_file: str = "data/karaoke_tracking.json") -> None:
    """Show statistics about current downloads."""
    if not os.path.exists(tracking_file):
        print("No tracking file found.")
        return
    
    with open(tracking_file, 'r', encoding='utf-8') as f:
        tracking = json.load(f)
    
    songs = tracking.get("songs", {})
    total_songs = len(songs)
    
    if total_songs == 0:
        print("No songs in tracking file.")
        return
    
    # Count by status
    status_counts = {}
    channel_counts = {}
    
    for song_id, song_data in songs.items():
        status = song_data.get("status", "UNKNOWN")
        channel = song_data.get("channel_name", "UNKNOWN")
        
        status_counts[status] = status_counts.get(status, 0) + 1
        channel_counts[channel] = channel_counts.get(channel, 0) + 1
    
    print(f"\n📊 Current Download Statistics:")
    print(f"Total songs: {total_songs}")
    print(f"\nBy Status:")
    for status, count in status_counts.items():
        print(f"  {status}: {count}")
    
    print(f"\nBy Channel:")
    for channel, count in channel_counts.items():
        print(f"  {channel}: {count}")


def main():
    """Main function to handle reset and re-download process."""
    print("🔄 Karaoke Download Reset and Re-download Tool")
    print("=" * 50)
    
    # Show current stats
    print("\nCurrent download statistics:")
    show_download_stats()
    
    # Ask user what they want to do
    print("\nOptions:")
    print("1. Reset tracking only (keep files)")
    print("2. Reset tracking and delete all downloaded files")
    print("3. Show current stats only")
    print("4. Exit")
    
    choice = input("\nEnter your choice (1-4): ").strip()
    
    if choice == "1":
        print("\n🔄 Resetting tracking only...")
        reset_karaoke_tracking()
        print("\n✅ Tracking reset complete!")
        print("You can now re-download files with the new channel parser system.")
        print("\nTo re-download, run:")
        print("python download_karaoke.py --file data/channels.txt --limit 50")
        
    elif choice == "2":
        print("\n🔄 Resetting tracking and deleting files...")
        confirm = input("Are you sure you want to delete ALL downloaded files? (yes/no): ").strip().lower()
        
        if confirm == "yes":
            reset_karaoke_tracking()
            delete_downloaded_files()
            print("\n✅ Reset complete! All tracking and files have been removed.")
            print("You can now re-download files with the new channel parser system.")
            print("\nTo re-download, run:")
            print("python download_karaoke.py --file data/channels.txt --limit 50")
        else:
            print("Operation cancelled.")
            
    elif choice == "3":
        print("\n📊 Current statistics:")
        show_download_stats()
        
    elif choice == "4":
        print("Exiting...")
        
    else:
        print("Invalid choice. Please enter 1, 2, 3, or 4.")


if __name__ == "__main__":
    main() 