import os
import unittest
from pathlib import Path
import tempfile
import shutil
from src.presets import PresetManager
from src.models import Preset

class TestPresetManager(unittest.TestCase):
 def setUp(self):
  self.test_dir = Path(tempfile.mkdtemp())
  self.project_root = self.test_dir / "project"
  self.project_root.mkdir()
  
  # Mocking global path is harder since it's hardcoded in paths.py
  # But we can at least test project-specific ones and the manager's logic.
  # For the sake of this test, we will only test what we can without 
  # affecting the real global_presets.toml if possible.
  
  self.manager = PresetManager(project_root=self.project_root)
  # Override paths for testing to avoid touching real files
  self.manager.global_path = self.test_dir / "global_presets.toml"

 def tearDown(self):
  shutil.rmtree(self.test_dir)

 def test_save_and_load_global(self):
  preset = Preset(name="test_global", system_prompt="You are a global assistant")
  self.manager.save_preset(preset, scope="global")
  
  presets = self.manager.load_all()
  self.assertIn("test_global", presets)
  self.assertEqual(presets["test_global"].system_prompt, "You are a global assistant")

 def test_save_and_load_project(self):
  preset = Preset(name="test_project", system_prompt="You are a project assistant")
  self.manager.save_preset(preset, scope="project")
  
  presets = self.manager.load_all()
  self.assertIn("test_project", presets)
  self.assertEqual(presets["test_project"].system_prompt, "You are a project assistant")

 def test_project_overwrites_global(self):
  g_preset = Preset(name="shared", system_prompt="Global version")
  p_preset = Preset(name="shared", system_prompt="Project version")
  
  self.manager.save_preset(g_preset, scope="global")
  self.manager.save_preset(p_preset, scope="project")
  
  presets = self.manager.load_all()
  self.assertEqual(presets["shared"].system_prompt, "Project version")

 def test_delete_preset(self):
  preset = Preset(name="to_delete", system_prompt="Delete me")
  self.manager.save_preset(preset, scope="project")
  
  presets = self.manager.load_all()
  self.assertIn("to_delete", presets)
  
  self.manager.delete_preset("to_delete", scope="project")
  presets = self.manager.load_all()
  self.assertNotIn("to_delete", presets)

 def test_dynamic_project_path(self):
  """Verifies that project_path updates when project_root changes."""
  initial_root = self.test_dir / "project1"
  initial_root.mkdir()
  manager = PresetManager(project_root=initial_root)
  self.assertEqual(manager.project_path, initial_root / "project_presets.toml")
  
  new_root = self.test_dir / "project2"
  new_root.mkdir()
  manager.project_root = new_root
  self.assertEqual(manager.project_path, new_root / "project_presets.toml")

if __name__ == "__main__":
 unittest.main()