from __future__ import annotations

import json
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any


@dataclass
class ConfigManager:
    path: Path
    defaults: dict[str, Any] = field(default_factory=dict)
    data: dict[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        self.path = Path(self.path)
        if not self.data:
            self.data = dict(self.defaults)

    def load(self) -> dict[str, Any]:
        if self.path.exists():
            try:
                payload = json.loads(self.path.read_text(encoding='utf-8'))
                self.data = {**self.defaults, **payload}
            except Exception:
                self.data = dict(self.defaults)
        return self.data

    def save(self) -> Path:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.path.write_text(json.dumps(self.data, indent=2), encoding='utf-8')
        return self.path

    def get(self, key: str, default: Any = None) -> Any:
        return self.data.get(key, default)

    def set(self, key: str, value: Any) -> None:
        self.data[key] = value

    def update(self, payload: dict[str, Any]) -> None:
        self.data.update(payload)


@dataclass
class WorkspaceProfile:
    name: str
    data: dict[str, Any] = field(default_factory=dict)


class WorkspaceProfileManager:
    def __init__(self, path: str | Path):
        self.path = Path(path)
        self.profiles: dict[str, WorkspaceProfile] = {}
        self.load()

    def load(self) -> dict[str, WorkspaceProfile]:
        if not self.path.exists():
            return self.profiles
        try:
            payload = json.loads(self.path.read_text(encoding='utf-8'))
        except Exception:
            return self.profiles
        self.profiles = {name: WorkspaceProfile(name, data) for name, data in payload.items()}
        return self.profiles

    def save(self) -> Path:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        raw = {name: profile.data for name, profile in self.profiles.items()}
        self.path.write_text(json.dumps(raw, indent=2), encoding='utf-8')
        return self.path

    def set(self, name: str, data: dict[str, Any]) -> WorkspaceProfile:
        profile = WorkspaceProfile(name=name, data=data)
        self.profiles[name] = profile
        return profile

    def get(self, name: str) -> WorkspaceProfile | None:
        return self.profiles.get(name)

    def names(self) -> list[str]:
        return sorted(self.profiles)
