import json
import os
import copy
from typing import Dict, Any, List

def load_characters(lang: str = "de") -> List[Dict[str, Any]]:
    """Load character data for given language."""
    if lang not in ["de", "en", "fr"]:
        lang = "de"

    # Assume we are running from app root
    characters_path = os.path.join('static', 'data', f'characters.{lang}.json')
    try:
        with open(characters_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        # Fallback to German
        try:
            with open(os.path.join('static', 'data', 'characters.de.json'), 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception:
             return []
    except Exception as e:
        print(f"Error loading characters: {e}")
        return []

def merge_role_localization(roles: Dict[str, Any], lang: str) -> Dict[str, Any]:
    """
    Return a deep copy of roles with localized content merged in.
    """
    localized_roles = copy.deepcopy(roles)
    localized_list = load_characters(lang)
    localized_map = {char.get('id'): char for char in localized_list}

    # Legacy ID mapping
    legacy_id_map = {
        'funkfox': 'fox',
        'schraubaer': 'schraubär',
        'capacitoby': 'capacitobi',
        'taichitaube': 'taichi',
        'taichi': 'taichi'
    }

    for role_id, role in localized_roles.items():
        lookup_id = legacy_id_map.get(role_id, role_id)
        
        if lookup_id in localized_map:
            l_data = localized_map[lookup_id]
            if 'name' in l_data:
                role['name'] = l_data['name']
            if 'description' in l_data:
                role['description'] = l_data['description']
            if 'short' in l_data:
                role['title'] = l_data['short'] # Map short to title if desired, or keep original title?
                # In the previous step I mapped 'title' in the JSON file directly. 
                # If JSON has 'title', use it.
                if 'title' in l_data:
                    role['title'] = l_data['title']
            if 'system_prompt' in l_data:
                role['system_prompt'] = l_data['system_prompt']
    
    return localized_roles
