"""Config store — JSON file with AES-encrypted API key. Uses only `cryptography`."""
from __future__ import annotations
import json, os
from pathlib import Path
from typing import Any

from doit_fm.config import CONFIG_FILE, DATA_DIR


class ConfigStore:
    def __init__(self):
        self._path = CONFIG_FILE
        self._data: dict = {}
        self._load()

    def _load(self):
        if self._path.exists():
            try:
                self._data = json.loads(self._path.read_text(encoding="utf-8"))
            except Exception:
                self._data = {}

    def _save(self):
        self._path.parent.mkdir(parents=True, exist_ok=True)
        out = dict(self._data)
        raw = out.get("ai_api_key", "")
        if raw and not str(raw).startswith("ENC:"):
            out["ai_api_key"] = _encrypt(raw)
        self._path.write_text(json.dumps(out, indent=2), encoding="utf-8")

    def get(self, key: str, default=None) -> Any:
        val = self._data.get(key, default)
        if key == "ai_api_key" and isinstance(val, str) and val.startswith("ENC:"):
            return _decrypt(val)
        return val

    def set(self, key: str, value: Any):
        self._data[key] = value
        self._save()

    def all(self) -> dict:
        out = dict(self._data)
        raw = out.get("ai_api_key", "")
        if isinstance(raw, str) and raw.startswith("ENC:"):
            out["ai_api_key"] = _decrypt(raw)
        return out

    def exists(self) -> bool:
        return bool(self._data.get("setup_complete"))


def _key_path() -> Path:
    return DATA_DIR / ".enc_key"

def _get_key() -> bytes:
    kp = _key_path()
    if kp.exists():
        return kp.read_bytes()
    from cryptography.fernet import Fernet
    kp.parent.mkdir(parents=True, exist_ok=True)
    k = Fernet.generate_key()
    kp.write_bytes(k)
    try:
        kp.chmod(0o600)
    except Exception:
        pass
    return k

def _encrypt(plaintext: str) -> str:
    try:
        from cryptography.fernet import Fernet
        return "ENC:" + Fernet(_get_key()).encrypt(plaintext.encode()).decode()
    except Exception:
        return plaintext

def _decrypt(ciphertext: str) -> str:
    try:
        from cryptography.fernet import Fernet
        return Fernet(_get_key()).decrypt(ciphertext[4:].encode()).decode()
    except Exception:
        return ciphertext[4:]


_store = None

def get_config():
    global _store
    if _store is None:
        _store = ConfigStore()
    return _store
