# backend/core/profile_manager.py from pathlib import Path import json from typing import Dict, Any, List, Optional from datetime import datetime class ProfileManager: """Manages configuration profiles""" DEFAULT_PROFILE = { "id": "default", "name": "Default Profile", "llm_settings": {"model": "gpt-4", "temperature": 0.7, "api_key": ""}, "created_at": "", "updated_at": "", } def __init__(self, data_dir: Path): self.data_dir = data_dir self.profiles_file = data_dir / "profiles.json" self.profiles: Dict[str, Dict] = self._load_profiles() def _load_profiles(self) -> Dict[str, Dict]: """Load profiles from file""" if self.profiles_file.exists(): try: with open(self.profiles_file, "r", encoding="utf-8") as f: profiles = json.load(f) # Ensure default profile exists if "default" not in profiles: profiles["default"] = self._create_default_profile() return profiles except Exception as e: print(f"Error loading profiles: {e}") return {"default": self._create_default_profile()} else: # Create directory if it doesn't exist self.profiles_file.parent.mkdir(parents=True, exist_ok=True) # Create default profile profiles = {"default": self._create_default_profile()} self._save_profiles(profiles) return profiles def _create_default_profile(self) -> Dict[str, Any]: """Create default profile with timestamp""" profile = self.DEFAULT_PROFILE.copy() now = datetime.now().isoformat() profile["created_at"] = now profile["updated_at"] = now return profile def _save_profiles(self, profiles: Optional[Dict] = None): """Save profiles to file""" if profiles is None: profiles = self.profiles try: print(f"Saving profiles to: {self.profiles_file}") # Agregar debug with open(self.profiles_file, "w", encoding="utf-8") as f: json.dump(profiles, f, indent=4) print("Profiles saved successfully") # Agregar debug except Exception as e: print(f"Error saving profiles: {e}") # Agregar debug raise # Re-lanzar la excepción para que se maneje arriba def get_all_profiles(self) -> List[Dict[str, Any]]: """Get all profiles""" return list(self.profiles.values()) def get_profile(self, profile_id: str) -> Optional[Dict[str, Any]]: """Get specific profile""" return self.profiles.get(profile_id) def create_profile(self, profile_data: Dict[str, Any]) -> Dict[str, Any]: """Create new profile""" if "id" not in profile_data: raise ValueError("Profile must have an id") profile_id = profile_data["id"] if profile_id in self.profiles: raise ValueError(f"Profile {profile_id} already exists") # Add timestamps now = datetime.now().isoformat() profile_data["created_at"] = now profile_data["updated_at"] = now # Ensure required fields for key in ["name", "llm_settings"]: if key not in profile_data: profile_data[key] = self.DEFAULT_PROFILE[key] self.profiles[profile_id] = profile_data self._save_profiles() return profile_data def update_profile( self, profile_id: str, profile_data: Dict[str, Any] ) -> Dict[str, Any]: """Update existing profile""" try: print(f"Updating profile {profile_id} with data: {profile_data}") if profile_id not in self.profiles: raise ValueError(f"Profile {profile_id} not found") if profile_id == "default" and "id" in profile_data: raise ValueError("Cannot change id of default profile") # Update timestamp profile_data["updated_at"] = datetime.now().isoformat() # Update profile current_profile = self.profiles[profile_id].copy() # Hacer una copia current_profile.update(profile_data) # Actualizar la copia self.profiles[profile_id] = current_profile # Asignar la copia actualizada print(f"Updated profile: {self.profiles[profile_id]}") self._save_profiles() return self.profiles[profile_id] except Exception as e: print(f"Error in update_profile: {e}") # Agregar debug raise def delete_profile(self, profile_id: str): """Delete profile""" if profile_id == "default": raise ValueError("Cannot delete default profile") if profile_id not in self.profiles: raise ValueError(f"Profile {profile_id} not found") del self.profiles[profile_id] self._save_profiles()