import os
import sys
from pathlib import Path
from src import models
from src.paths import get_config_path, get_global_presets_path, get_project_presets_path
from src.presets import PresetManager
from src.personas import PersonaManager

def migrate():
    print("Starting Persona Migration...")
    
    config_path = get_config_path()
    try:
        with open(config_path, "rb") as f:
            import tomllib
            config = tomllib.load(f)
    except Exception as e:
        print(f"Could not load config: {e}")
        return

    ai_cfg = config.get("ai", {})
    provider = ai_cfg.get("provider")
    model = ai_cfg.get("model")
    
    global_presets_path = get_global_presets_path()
    preset_manager = PresetManager()
    
    persona_manager = PersonaManager()
    
    # Migrate global presets
    if global_presets_path.exists():
        global_data = preset_manager._load_file(global_presets_path)
        for name, data in global_data.get("presets", {}).items():
            preset = models.Preset.from_dict(name, data)
            persona = models.Persona(
                name=name,
                preferred_models=[{"provider": provider, "model": model}],
                system_prompt=preset.system_prompt
            )
            persona_manager.save_persona(persona, scope="global")
            print(f"Migrated global preset to persona: {name}")

    # Create Initial Legacy Persona from config if not in presets
    active_preset = ai_cfg.get("active_preset")
    if active_preset and active_preset not in persona_manager.load_all():
         persona = models.Persona(
             name=active_preset,
             preferred_models=[{
                 "provider": provider,
                 "model": model,
                 "temperature": ai_cfg.get("temperature"),
                 "max_output_tokens": ai_cfg.get("max_tokens")
             }],
             system_prompt=ai_cfg.get("system_prompt", "")
         )
         persona_manager.save_persona(persona, scope="global")
         print(f"Created Initial Legacy persona from active_preset: {active_preset}")
         
    print("Migration complete.")

if __name__ == "__main__":
    migrate()
