import os

from pathlib import Path

from karaoke_downloader.songlist_manager import (
    is_songlist_song_downloaded,
    normalize_title,
    save_songlist_tracking,
)


def reset_channel_downloads(
    tracker,
    songlist_tracking,
    songlist_tracking_file,
    channel_name,
    reset_songlist=False,
    delete_files=False,
):
    """
    Reset all tracking and optionally files for a channel.
    If reset_songlist is False, songlist songs are preserved (tracking and files).
    If reset_songlist is True, songlist songs for this channel are also reset/deleted.
    """
    print(
        f"\n🔄 Resetting channel: {channel_name} (reset_songlist={reset_songlist}, delete_files={delete_files})"
    )
    # Find channel_id from channel_name
    channel_id = None
    for pid, playlist in tracker.data.get("playlists", {}).items():
        if playlist["name"] == channel_name or pid == channel_name:
            channel_id = pid
            break
    if not channel_id:
        print(f"❌ Channel '{channel_name}' not found in tracking.")
        return
    # Get all songs for this channel
    songs_to_reset = []
    for song_id, song in tracker.data.get("songs", {}).items():
        if song["playlist_id"] == channel_id:
            # Check if this is a songlist song
            artist, title = song.get("artist", ""), song.get(
                "title", song.get("name", "")
            )
            key = f"{artist.lower()}_{normalize_title(title)}"
            is_songlist = key in songlist_tracking
            if is_songlist and not reset_songlist:
                continue  # skip songlist songs if not resetting them
            songs_to_reset.append((song_id, song, is_songlist))
    # Reset tracking and optionally delete files
    files_preserved = 0
    files_deleted = 0
    for song_id, song, is_songlist in songs_to_reset:
        # Remove from main tracking
        tracker.data["songs"][song_id]["status"] = "NOT_DOWNLOADED"
        tracker.data["songs"][song_id]["formats"] = {}
        tracker.data["songs"][song_id]["last_error"] = ""
        tracker.data["songs"][song_id]["download_attempts"] = 0
        tracker.data["songs"][song_id]["last_updated"] = None
        # Remove from songlist tracking if needed
        if is_songlist and reset_songlist:
            artist, title = song.get("artist", ""), song.get(
                "title", song.get("name", "")
            )
            key = f"{artist.lower()}_{normalize_title(title)}"
            if key in songlist_tracking:
                del songlist_tracking[key]
        # Delete file if requested
        if delete_files:
            file_path = song.get("file_path")
            if file_path:
                try:
                    p = Path(file_path)
                    if p.exists():
                        p.unlink()
                        files_deleted += 1
                    else:
                        files_preserved += 1
                except Exception as e:
                    print(f"⚠️ Could not delete file {file_path}: {e}")
    # Remove all songlist_tracking entries for this channel if reset_songlist is True
    if reset_songlist:
        keys_to_remove = [
            k for k, v in songlist_tracking.items() if v.get("channel") == channel_name
        ]
        for k in keys_to_remove:
            del songlist_tracking[k]
    # Save changes
    tracker.force_save()
    save_songlist_tracking(songlist_tracking, str(songlist_tracking_file))
    print(f"✅ Reset {len(songs_to_reset)} songs for channel '{channel_name}'.")
    if delete_files:
        print(f"   Files deleted: {files_deleted}, files preserved: {files_preserved}")
    if not reset_songlist:
        print("   Songlist songs were preserved.")


def download_from_file(self, file_path, force_refresh=False):
    file = Path(file_path)
    if not file.exists():
        print(f"❌ File not found: {file_path}")
        return False
    with open(file, "r", encoding="utf-8") as f:
        urls = [
            line.strip()
            for line in f
            if line.strip() and not line.strip().startswith("#")
        ]
    if not urls:
        print(f"❌ No URLs found in {file_path}")
        return False
    all_success = True
    for url in urls:
        print(f"\n➡️  Processing: {url}")
        success = self.download_channel_videos(url, force_refresh=force_refresh)
        if not success:
            all_success = False
    return all_success
