import sys

with open("src/gui_2.py", "r", encoding="utf-8") as f:
    content = f.read()

# 1. Update _gui_func:
# Extract Persona out of Provider panel. I will create a new method _render_persona_selector_panel
old_gui_settings = """   if self.show_windows.get("AI Settings", False):
    exp, opened = imgui.begin("AI Settings", self.show_windows["AI Settings"])
    self.show_windows["AI Settings"] = bool(opened)
    if exp:
     if imgui.collapsing_header("Provider & Model"):
      self._render_provider_panel()
     if imgui.collapsing_header("System Prompts"):
      self._render_system_prompts_panel()
     self._render_agent_tools_panel()
     self._render_cache_panel()

    imgui.end()
   if self.ui_separate_usage_analytics and self.show_windows.get("Usage Analytics", False):
    exp, opened = imgui.begin("Usage Analytics", self.show_windows["Usage Analytics"])
    self.show_windows["Usage Analytics"] = bool(opened)
    if exp:
     self._render_usage_analytics_panel()
    imgui.end()"""

new_gui_settings = """   if self.show_windows.get("AI Settings", False):
    exp, opened = imgui.begin("AI Settings", self.show_windows["AI Settings"])
    self.show_windows["AI Settings"] = bool(opened)
    if exp:
     self._render_persona_selector_panel()
     if imgui.collapsing_header("Provider & Model"):
      self._render_provider_panel()
     if imgui.collapsing_header("System Prompts"):
      self._render_system_prompts_panel()
     self._render_agent_tools_panel()

    imgui.end()
   if self.ui_separate_usage_analytics and self.show_windows.get("Usage Analytics", False):
    exp, opened = imgui.begin("Usage Analytics", self.show_windows["Usage Analytics"])
    self.show_windows["Usage Analytics"] = bool(opened)
    if exp:
     self._render_usage_analytics_panel()
    imgui.end()"""

content = content.replace(old_gui_settings, new_gui_settings)

# Update _render_usage_analytics_panel
old_usage = """ def _render_usage_analytics_panel(self) -> None:
  if self.perf_profiling_enabled: self.perf_monitor.start_component("_render_usage_analytics_panel")
  self._render_token_budget_panel()
  imgui.separator()
  self._render_tool_analytics_panel()
  imgui.separator()
  self._render_session_insights_panel()
  if self.perf_profiling_enabled: self.perf_monitor.end_component("_render_usage_analytics_panel")"""

new_usage = """ def _render_usage_analytics_panel(self) -> None:
  if self.perf_profiling_enabled: self.perf_monitor.start_component("_render_usage_analytics_panel")
  self._render_token_budget_panel()
  imgui.separator()
  self._render_cache_panel()
  imgui.separator()
  self._render_tool_analytics_panel()
  imgui.separator()
  self._render_session_insights_panel()
  if self.perf_profiling_enabled: self.perf_monitor.end_component("_render_usage_analytics_panel")"""
content = content.replace(old_usage, new_usage)

# Remove the persona block from _render_provider_panel and put it in _render_persona_selector_panel
old_persona_block = """ def _render_provider_panel(self) -> None:
  if self.perf_profiling_enabled: self.perf_monitor.start_component("_render_provider_panel")
  imgui.text("Persona")
  if not hasattr(self, 'ui_active_persona'):
   self.ui_active_persona = ""
  personas = getattr(self.controller, 'personas', {})
  if imgui.begin_combo("##persona", self.ui_active_persona or "None"):
   if imgui.selectable("None", not self.ui_active_persona)[0]:
    self.ui_active_persona = ""
   for pname in sorted(personas.keys()):
    if imgui.selectable(pname, pname == self.ui_active_persona)[0]:
     self.ui_active_persona = pname
     if pname in personas:
      persona = personas[pname]
      self._editing_persona_name = persona.name
      self._editing_persona_provider = persona.provider or ""
      self._editing_persona_model = persona.model or ""
      self._editing_persona_system_prompt = persona.system_prompt or ""
      self._editing_persona_temperature = persona.temperature or 0.7
      self._editing_persona_max_tokens = persona.max_output_tokens or 4096
      self._editing_persona_tool_preset_id = persona.tool_preset or ""
      self._editing_persona_bias_profile_id = persona.bias_profile or ""
      import json
      self._editing_persona_preferred_models = json.dumps(persona.preferred_models) if persona.preferred_models else "[]"
      self._editing_persona_is_new = False
      if persona.provider and persona.provider in self.controller.PROVIDERS:
       self.current_provider = persona.provider
      if persona.model:
       self.current_model = persona.model
      if persona.temperature is not None:
       ai_client.temperature = persona.temperature
      if persona.max_output_tokens:
       ai_client.max_output_tokens = persona.max_output_tokens
      if persona.system_prompt:
       self.ui_project_system_prompt = persona.system_prompt
      if persona.tool_preset:
       self.ui_active_tool_preset = persona.tool_preset
       ai_client.set_tool_preset(persona.tool_preset)
      if persona.bias_profile:
       self.ui_active_bias_profile = persona.bias_profile
       ai_client.set_bias_profile(persona.bias_profile)
   imgui.end_combo()
  imgui.same_line()
  if imgui.button("Manage Personas"):
   self.show_persona_editor_window = True
   if self.ui_active_persona and self.ui_active_persona in personas:
    persona = personas[self.ui_active_persona]
    self._editing_persona_name = persona.name
    self._editing_persona_provider = persona.provider or ""
    self._editing_persona_model = persona.model or ""
    self._editing_persona_system_prompt = persona.system_prompt or ""
    self._editing_persona_temperature = persona.temperature if persona.temperature is not None else 0.7
    self._editing_persona_max_tokens = persona.max_output_tokens if persona.max_output_tokens is not None else 4096
    self._editing_persona_tool_preset_id = persona.tool_preset or ""
    self._editing_persona_bias_profile_id = persona.bias_profile or ""
    self._editing_persona_preferred_models_list = list(persona.preferred_models) if persona.preferred_models else []
    self._editing_persona_scope = self.controller.persona_manager.get_persona_scope(persona.name)
    self._editing_persona_is_new = False
   else:
    self._editing_persona_name = ""
    self._editing_persona_provider = self.current_provider
    self._editing_persona_model = self.current_model
    self._editing_persona_system_prompt = ""
    self._editing_persona_temperature = 0.7
    self._editing_persona_max_tokens = 4096
    self._editing_persona_tool_preset_id = ""
    self._editing_persona_bias_profile_id = ""
    self._editing_persona_preferred_models_list = []
    self._editing_persona_scope = "project"
    self._editing_persona_is_new = True
  imgui.separator()
  imgui.text("Provider")"""

new_persona_block = """ def _render_persona_selector_panel(self) -> None:
  if self.perf_profiling_enabled: self.perf_monitor.start_component("_render_persona_selector_panel")
  imgui.text("Persona")
  if not hasattr(self, 'ui_active_persona'):
   self.ui_active_persona = ""
  personas = getattr(self.controller, 'personas', {})
  if imgui.begin_combo("##persona", self.ui_active_persona or "None"):
   if imgui.selectable("None", not self.ui_active_persona)[0]:
    self.ui_active_persona = ""
   for pname in sorted(personas.keys()):
    if imgui.selectable(pname, pname == self.ui_active_persona)[0]:
     self.ui_active_persona = pname
     if pname in personas:
      persona = personas[pname]
      self._editing_persona_name = persona.name
      self._editing_persona_system_prompt = persona.system_prompt or ""
      self._editing_persona_tool_preset_id = persona.tool_preset or ""
      self._editing_persona_bias_profile_id = persona.bias_profile or ""
      import copy
      self._editing_persona_preferred_models_list = copy.deepcopy(persona.preferred_models) if persona.preferred_models else []
      self._editing_persona_is_new = False
      
      # Apply persona to current state immediately
      if persona.preferred_models and len(persona.preferred_models) > 0:
       first_model = persona.preferred_models[0]
       if first_model.get("provider"):
        self.current_provider = first_model.get("provider")
       if first_model.get("model"):
        self.current_model = first_model.get("model")
       if first_model.get("temperature") is not None:
        ai_client.temperature = first_model.get("temperature")
        self.temperature = first_model.get("temperature")
       if first_model.get("max_output_tokens"):
        ai_client.max_output_tokens = first_model.get("max_output_tokens")
        self.max_tokens = first_model.get("max_output_tokens")
       if first_model.get("history_trunc_limit"):
        self.history_trunc_limit = first_model.get("history_trunc_limit")
      
      if persona.system_prompt:
       self.ui_project_system_prompt = persona.system_prompt
      if persona.tool_preset:
       self.ui_active_tool_preset = persona.tool_preset
       ai_client.set_tool_preset(persona.tool_preset)
      if persona.bias_profile:
       self.ui_active_bias_profile = persona.bias_profile
       ai_client.set_bias_profile(persona.bias_profile)
   imgui.end_combo()
  imgui.same_line()
  if imgui.button("Manage Personas"):
   self.show_persona_editor_window = True
   if self.ui_active_persona and self.ui_active_persona in personas:
    persona = personas[self.ui_active_persona]
    self._editing_persona_name = persona.name
    self._editing_persona_system_prompt = persona.system_prompt or ""
    self._editing_persona_tool_preset_id = persona.tool_preset or ""
    self._editing_persona_bias_profile_id = persona.bias_profile or ""
    import copy
    self._editing_persona_preferred_models_list = copy.deepcopy(persona.preferred_models) if persona.preferred_models else []
    self._editing_persona_scope = self.controller.persona_manager.get_persona_scope(persona.name)
    self._editing_persona_is_new = False
   else:
    self._editing_persona_name = ""
    self._editing_persona_system_prompt = ""
    self._editing_persona_tool_preset_id = ""
    self._editing_persona_bias_profile_id = ""
    self._editing_persona_preferred_models_list = [{
     "provider": self.current_provider,
     "model": self.current_model,
     "temperature": getattr(self, "temperature", 0.7),
     "max_output_tokens": getattr(self, "max_tokens", 4096),
     "history_trunc_limit": getattr(self, "history_trunc_limit", 900000)
    }]
    self._editing_persona_scope = "project"
    self._editing_persona_is_new = True
  imgui.separator()
  if self.perf_profiling_enabled: self.perf_monitor.end_component("_render_persona_selector_panel")

 def _render_provider_panel(self) -> None:
  if self.perf_profiling_enabled: self.perf_monitor.start_component("_render_provider_panel")
  imgui.text("Provider")"""
content = content.replace(old_persona_block, new_persona_block)

with open("src/gui_2.py", "w", encoding="utf-8") as f:
    f.write(content)
print("done gui updates")
