import unittest
from unittest.mock import MagicMock, patch
import os
import sys
from pathlib import Path

# Add src to sys.path if needed
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from src import ai_client
from src.app_controller import AppController
from src import models

class TestSystemPromptExposure(unittest.TestCase):

 def setUp(self):
  # Reset ai_client globals
  ai_client.set_use_default_base_prompt(True)
  ai_client.set_base_system_prompt("")
  ai_client.set_custom_system_prompt("")

 def test_ai_client_get_combined_respects_use_default(self):
  # 1. Verify ai_client._get_combined_system_prompt() respects set_use_default_base_prompt()
  
  # Default is True, should return _SYSTEM_PROMPT
  default_prompt = ai_client._get_combined_system_prompt()
  self.assertIn("You are a helpful coding assistant", default_prompt)
  
  # Set to False, should return override (empty by default)
  ai_client.set_use_default_base_prompt(False)
  override_prompt = ai_client._get_combined_system_prompt()
  self.assertEqual(override_prompt, "")
  
  # Set override and verify
  ai_client.set_base_system_prompt("Custom Base")
  override_prompt = ai_client._get_combined_system_prompt()
  self.assertEqual(override_prompt, "Custom Base")

 def test_ai_client_set_base_overrides_when_default_false(self):
  # 2. Verify ai_client.set_base_system_prompt() correctly overrides the base when use_default is False.
  ai_client.set_use_default_base_prompt(False)
  ai_client.set_base_system_prompt("Overridden Prompt")
  combined = ai_client._get_combined_system_prompt()
  self.assertEqual(combined, "Overridden Prompt")
  
  # If we switch back to default, it should ignore the override
  ai_client.set_use_default_base_prompt(True)
  combined = ai_client._get_combined_system_prompt()
  self.assertIn("You are a helpful coding assistant", combined)
  self.assertNotIn("Overridden Prompt", combined)

 @patch('src.app_controller.AppController.load_config')
 @patch('src.paths.get_full_path_info')
 @patch('src.project_manager.load_project')
 @patch('src.ai_client.set_tool_preset')
 @patch('src.ai_client.set_bias_profile')
 @patch('src.session_logger.reset_session')
 def test_app_controller_init_state_loads_prompts(self, mock_reset, mock_bias, mock_preset, mock_load_project, mock_path_info, mock_load_config):
  # 3. Verify AppController.init_state() correctly loads base_system_prompt and use_default_base_prompt from a mock config.
  
  mock_config = {
   "ai": {
    "base_system_prompt": "Config Base Prompt",
    "use_default_base_prompt": False,
    "provider": "gemini",
    "model": "gemini-2.5-flash-lite"
   },
   "projects": {"paths": [], "active": ""},
   "gui": {"show_windows": {}}
  }
  mock_load_config.return_value = mock_config
  mock_path_info.return_value = {
   'logs_dir': {'path': Path('logs')},
   'scripts_dir': {'path': Path('scripts')}
  }
  mock_load_project.return_value = {}
  
  app = AppController()
  # Mock the event queue to avoid thread errors
  app.event_queue = MagicMock()
  
  app.init_state()
  
  self.assertEqual(app.ui_base_system_prompt, "Config Base Prompt")
  self.assertEqual(app.ui_use_default_base_prompt, False)

 def test_app_controller_flush_saves_prompts(self):
  # 4. Verify AppController._flush_to_config() correctly saves these fields.
  app = AppController()
  app.config = {"ai": {}, "projects": {}, "gui": {}}
  app.ui_base_system_prompt = "Flushed Prompt"
  app.ui_use_default_base_prompt = True
  app.ui_global_system_prompt = "Global Sys"
  app.ui_global_preset_name = "Default"
  app.project_paths = []
  app.active_project_path = ""
  
  # Initialize missing attributes expected by _flush_to_config
  app.ui_separate_task_dag = False
  app.ui_separate_usage_analytics = False
  app.ui_separate_tier1 = False
  app.ui_separate_tier2 = False
  app.ui_separate_tier3 = False
  app.ui_separate_tier4 = False
  
  # Mock current_provider/model properties
  with patch.object(AppController, 'current_provider', 'gemini'), \
       patch.object(AppController, 'current_model', 'gemini-model'):
   app._flush_to_config()
  
  self.assertEqual(app.config["ai"]["base_system_prompt"], "Flushed Prompt")
  self.assertEqual(app.config["ai"]["use_default_base_prompt"], True)

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