"""Profiles persistence for PyUcc. Stores user profiles as JSON in the application directory (where the executable is located, `profiles.json`). Each profile is a dict with keys: - name: str - path: str - languages: list[str] - ignore: list[str] This module exposes simple load/save/manage helpers. """ from pathlib import Path import json import sys from typing import List, Dict, Optional # Get the directory where the application is running from # If frozen (PyInstaller), use the executable's directory # Otherwise use the directory of this module if getattr(sys, 'frozen', False): # Running as compiled executable _APP_DIR = Path(sys.executable).parent else: # Running as script - go up from config/ to pyucc/ to root _APP_DIR = Path(__file__).parent.parent.parent _DEFAULT_PATH = _APP_DIR / "profiles.json" def _read_file(path: Path) -> List[Dict]: if not path.exists(): return [] try: with path.open("r", encoding="utf-8") as fh: data = json.load(fh) if isinstance(data, list): return data except Exception: return [] return [] def _write_file(path: Path, profiles: List[Dict]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as fh: json.dump(profiles, fh, indent=2, ensure_ascii=False) def load_profiles(path: Optional[Path] = None) -> List[Dict]: """Return list of profiles from storage.""" p = path or _DEFAULT_PATH return _read_file(p) def save_profiles(profiles: List[Dict], path: Optional[Path] = None) -> None: """Persist profiles to storage.""" p = path or _DEFAULT_PATH _write_file(p, profiles) def find_profile(name: str, path: Optional[Path] = None) -> Optional[Dict]: """Return profile dict by name or None if not found.""" profiles = load_profiles(path) for pr in profiles: if pr.get("name") == name: return pr return None def add_or_update_profile(profile: Dict, path: Optional[Path] = None) -> None: """Add new profile or update existing one by name.""" p = path or _DEFAULT_PATH profiles = load_profiles(p) for i, pr in enumerate(profiles): if pr.get("name") == profile.get("name"): profiles[i] = profile save_profiles(profiles, p) return profiles.append(profile) save_profiles(profiles, p) def delete_profile(name: str, path: Optional[Path] = None) -> None: """Delete profile by name if exists.""" p = path or _DEFAULT_PATH profiles = load_profiles(p) profiles = [pr for pr in profiles if pr.get("name") != name] save_profiles(profiles, p)