from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any

from core_db import MASTER_KEY_FILE, SECRETS_ROOT, ensure_dirs

def _fernet():
    try:
        from cryptography.fernet import Fernet
    except ImportError as exc:
        raise RuntimeError("Не установлен пакет cryptography.") from exc

    ensure_dirs()
    if MASTER_KEY_FILE.exists():
        key = MASTER_KEY_FILE.read_bytes().strip()
    else:
        key = Fernet.generate_key()
        MASTER_KEY_FILE.write_bytes(key)
        try:
            os.chmod(MASTER_KEY_FILE, 0o600)
        except OSError:
            pass
    return Fernet(key)

def _path(connector: str) -> Path:
    safe = "".join(ch for ch in connector.lower() if ch.isalnum() or ch in "_-")
    if not safe:
        raise ValueError("Некорректный connector key")
    return SECRETS_ROOT / f"{safe}.enc"

def save_secret(connector: str, payload: dict[str, Any]) -> None:
    ensure_dirs()
    data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
    path = _path(connector)
    path.write_bytes(_fernet().encrypt(data))
    try:
        os.chmod(path, 0o600)
    except OSError:
        pass

def load_secret(connector: str, required: bool = True) -> dict[str, Any]:
    path = _path(connector)
    if not path.exists():
        if required:
            raise RuntimeError(f"Секреты connector «{connector}» не настроены.")
        return {}
    try:
        raw = _fernet().decrypt(path.read_bytes())
        obj = json.loads(raw.decode("utf-8"))
        return obj if isinstance(obj, dict) else {}
    except Exception as exc:
        raise RuntimeError(f"Не удалось прочитать секреты connector «{connector}».") from exc

def configured(connector: str) -> bool:
    return _path(connector).exists() and MASTER_KEY_FILE.exists()
