import os
import json

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(os.path.dirname(BASE_DIR))

# Determine config directory based on platform
def get_config_dir():
    """Get platform-appropriate config directory."""
    if os.name == 'nt':  # Windows
        config_base = os.environ.get('APPDATA', os.path.expanduser('~'))
    else:  # macOS and Linux
        config_base = os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
    
    config_dir = os.path.join(config_base, 'internetfilm_manager')
    
    # Create directory if it doesn't exist
    os.makedirs(config_dir, exist_ok=True)
    
    return config_dir

CONFIG_DIR = get_config_dir()
CONFIG_PATH = os.path.join(CONFIG_DIR, "config.json")

# Legacy config path for migration
LEGACY_CONFIG_PATH = os.path.join(ROOT_DIR, "config.json")

def load_config():
    """Lädt die Konfiguration."""
    defaults = {
        "work_dir": os.path.expanduser("~/Movies/Internetfilme/Work"),
        "archive_file": os.path.expanduser("~/Movies/Internetfilme/archive.txt"),
        "claude_key": "",
        "claude_model": "claude-sonnet-4-20250514",
        "claude_model_light": "",
        "rclone_root": "lyssach-nas:/Emby/media/Internetfilme",
        "rclone_master_root": "lyssach-nas:/Emby/media/Internetfilme",
        "ffmpeg": "ffmpeg",
        "ffprobe": "ffprobe",
        "ytdlp": "yt-dlp",
        "wait_time_playlist_sec": 5,
        "wait_time_download_queue_sec": 5,
        "wait_time_ytdlp_min_sec": 5,
        "wait_time_ytdlp_max_sec": 10,
        "retry_on_failure": False,
        "retry_wait_minutes": 30,
        "max_retries": 3,
        "require_thumbnail": True,
        "video_quality": 70,
        "bitrate_threshold_mbps": 100,
        "adaptive_quality_step": 2,
        "audio_fadeout_enabled": True,
        "video_targets": ["Allgemein", "Patrick", "Eltern", "Kathrin", "Kinder"],
        "music_target": "Musikvideos",
        "classification_enabled": False,
        "classification_rules_threshold": 10,
        "videos_since_last_rule_update": 0,
        "auto_download_playlists": [],
        "chapters_enabled": True,
        "fanart_enabled": False
    }
    
    # Check for legacy config and migrate if needed
    if not os.path.exists(CONFIG_PATH) and os.path.exists(LEGACY_CONFIG_PATH):
        try:
            print(f"🔄 Migriere Konfiguration von {LEGACY_CONFIG_PATH} nach {CONFIG_PATH}")
            with open(LEGACY_CONFIG_PATH, "r") as f:
                legacy_data = json.load(f)
            
            # Write to new location
            with open(CONFIG_PATH, "w", encoding="utf-8") as f:
                json.dump(legacy_data, f, indent=4, ensure_ascii=False)
            
            print(f"✅ Konfiguration erfolgreich migriert nach {CONFIG_PATH}")
            print(f"💡 Die alte Konfiguration unter {LEGACY_CONFIG_PATH} kann gelöscht werden.")
        except Exception as e:
            print(f"⚠️  Fehler bei der Migration der Config: {e}")
    
    if os.path.exists(CONFIG_PATH):
        try:
            with open(CONFIG_PATH, "r") as f:
                data = json.load(f)
                defaults.update(data)
                # Migrate legacy handbrake_quality → video_quality
                if "handbrake_quality" in data and "video_quality" not in data:
                    defaults["video_quality"] = data["handbrake_quality"]
                # Fallback, falls master_root in alter Config fehlt
                if "rclone_master_root" not in defaults:
                    defaults["rclone_master_root"] = defaults["rclone_root"]
        except Exception as e:
            print(f"⚠️  Fehler beim Laden der Config: {e}")
    
    return defaults

CONFIG = load_config()

def update_config(key, value):
    global CONFIG
    CONFIG[key] = value
    try:
        with open(CONFIG_PATH, "w", encoding="utf-8") as f:
            json.dump(CONFIG, f, indent=4, ensure_ascii=False)
        print("✅ Konfiguration gespeichert.")
        return True
    except Exception as e:
        print(f"❌ Fehler beim Speichern: {e}")
        return False

def get_available_targets():
    """
    Get list of all available target directories (video targets + music target).
    
    Returns a copy to prevent external code from modifying the config directly.
    Use update_config() to modify target lists persistently.
    
    Returns:
        List of target directory names (copy of internal config)
    """
    targets = CONFIG.get("video_targets", ["Allgemein"])[:]  # Create a copy
    music_target = CONFIG.get("music_target", "Musikvideos")
    if music_target and music_target not in targets:
        targets.append(music_target)
    
    # Add "Auto" option if classification is enabled
    if CONFIG.get("classification_enabled", False):
        if "Auto" not in targets:
            targets.append("Auto")
    
    return targets

def get_model_name(light=False):
    """Returns the appropriate Claude model name.
    
    Args:
        light: If True, returns the light model if configured, otherwise the main model.
    
    Returns:
        The Claude model name to use.
    """
    if light:
        light_model = CONFIG.get("claude_model_light", "")
        if light_model:
            return light_model
    return CONFIG.get("claude_model", "claude-sonnet-4-20250514")