import os
import json
import subprocess
from typing import List, Tuple, Optional, Dict
import sys

def load_selection() -> Dict:
    """Load selected character file paths and worldview

    Returns:
        Dict: Contains character file paths and worldview path
    """
    try:
        with open('selected_characters.json', 'r', encoding='utf-8') as f:
            data = json.load(f)
            return {
                "selected_files": data.get("selected_files", []),
                "selected_worldview": data.get("selected_worldview")
            }
    except (FileNotFoundError, json.JSONDecodeError, KeyError) as e:
        print(f"Failed to load selected characters and worldview: {e}")
        return {"selected_files": [], "selected_worldview": None}

def load_selected_characters() -> List[str]:
    """Load selected character file paths (backward compatibility)

    Returns:
        List[str]: Character file paths, if no selection result is found, return an empty list
    """
    selection = load_selection()
    return selection["selected_files"]

def load_selected_worldview() -> Optional[str]:
    """Load selected worldview file path

    Returns:
        Optional[str]: Worldview file path, if not found, return None
    """
    selection = load_selection()
    return selection["selected_worldview"]

def launch_selector(open_browser: bool = True) -> None:
    """Launch character selector server

    Args:
        open_browser (bool, optional): Whether to automatically open browser. Defaults to True.
    """
    # Check if app.py exists
    server_path = os.path.join(os.path.dirname(__file__), "app.py")
    if not os.path.exists(server_path):
        print(f"Error: Character selector server script not found {server_path}")
        return
    
    # Build launch command
    python_executable = sys.executable or "python"
    cmd = [python_executable, server_path]
    
    # Launch server process
    try:
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print(f"Launched character selector server (PID: {process.pid})")
        
        # Wait for server to start
        import time
        time.sleep(2)
        
        # Automatically open browser
        if open_browser:
            import webbrowser
            webbrowser.open("http://localhost:1210")
            print("Opened browser, please close the server after selection")
        
        print("Hint: Press Ctrl+C to close the server")
        
        # Wait for server process to end
        process.wait()
    except KeyboardInterrupt:
        print("\nReceived interrupt signal, closing server...")
        process.terminate()
        process.wait()
        print("Server closed")
    except Exception as e:
        print(f"Failed to launch character selector server: {e}")

def integrate_with_dialogue_generation() -> Tuple[Optional[str], Optional[List[str]]]:
    """Integrate with dialogue generation process

    Returns:
        Tuple[Optional[str], Optional[List[str]]]: 
            Selected worldview file path and character file paths
            If user cancels, return (None, None)
    """
    print("Launching Syntheic Character Pool...")
    launch_selector()
    
    # Load selection result
    selection = load_selection()
    selected_worldview = selection["selected_worldview"]
    selected_characters = selection["selected_files"]
    
    if not selected_worldview:
        print("No worldview selected, cannot continue")
        return None, None
        
    if not selected_characters or len(selected_characters) < 2:
        print("No enough characters selected (at least 2), cannot continue")
        return None, None
    
    print(f"Selected worldview: {selected_worldview}")
    print(f"Selected {len(selected_characters)} characters:")
    for i, path in enumerate(selected_characters, 1):
        print(f"{i}. {path}")
    
    return selected_worldview, selected_characters