import pytest
import tomli_w
from pathlib import Path
from src.models import Persona
from src.personas import PersonaManager
from src import paths

@pytest.fixture
def temp_paths(tmp_path, monkeypatch):
 global_dir = tmp_path / "global"
 global_dir.mkdir()
 project_dir = tmp_path / "project"
 project_dir.mkdir()
 
 global_path = global_dir / "personas.toml"
 project_path = project_dir / "project_personas.toml"
 
 monkeypatch.setattr(paths, "get_global_personas_path", lambda: global_path)
 monkeypatch.setattr(paths, "get_project_personas_path", lambda _: project_path)
 
 return {"global": global_path, "project": project_path, "project_root": project_dir}

def test_load_all_merged(temp_paths):
 global_data = {
  "personas": {
   "default": {
    "provider": "anthropic",
    "model": "claude-3",
    "system_prompt": "Global prompt"
   },
   "global_only": {
    "provider": "gemini",
    "system_prompt": "Gemini prompt"
   }
  }
 }
 with open(temp_paths["global"], "wb") as f:
  tomli_w.dump(global_data, f)
 
 project_data = {
  "personas": {
   "default": {
    "provider": "anthropic",
    "model": "claude-3.5", # Overrides global
    "system_prompt": "Project prompt"
   }
  }
 }
 with open(temp_paths["project"], "wb") as f:
  tomli_w.dump(project_data, f)
 
 manager = PersonaManager(project_root=temp_paths["project_root"])
 all_personas = manager.load_all()
 
 assert "global_only" in all_personas
 assert "default" in all_personas
 assert all_personas["default"].model == "claude-3.5"
 assert all_personas["default"].system_prompt == "Project prompt"

def test_save_persona(temp_paths):
 manager = PersonaManager(project_root=temp_paths["project_root"])
 persona = Persona(name="New", preferred_models=[{"provider": "gemini"}], system_prompt="Test")
 
 manager.save_persona(persona, scope="project")
 loaded = manager.load_all()
 assert "New" in loaded
 assert loaded["New"].provider == "gemini"

def test_delete_persona(temp_paths):
 project_data = {
  "personas": {
   "to_delete": {"provider": "gemini", "system_prompt": "Del"}
  }
 }
 with open(temp_paths["project"], "wb") as f:
  tomli_w.dump(project_data, f)
 
 manager = PersonaManager(project_root=temp_paths["project_root"])
 manager.delete_persona("to_delete", scope="project")
 loaded = manager.load_all()
 assert "to_delete" not in loaded
