"""Profiles persistence for PyUcc.

Stores user profiles as JSON in the user's home directory
(`~/.pyucc_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
from typing import List, Dict, Optional

_DEFAULT_PATH = Path.home() / ".pyucc_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)
