"""
neurocli config — API keys, permission tiers, settings
"""
import os
import json
from pathlib import Path

# SmartIDE/Android safe: use NEUROCLI_HOME env var if set, else ~/.neurocli
_home = Path(os.environ.get("NEUROCLI_HOME", "") or Path.home())
CONFIG_DIR = _home / ".neurocli"
CONFIG_FILE = CONFIG_DIR / "config.json"
MEMORY_FILE = CONFIG_DIR / "memory.json"
SESSIONS_DB = CONFIG_DIR / "sessions.db"
SNAPSHOTS_DIR = CONFIG_DIR / "snapshots"
STATS_FILE = CONFIG_DIR / "stats.json"

DEFAULT_CONFIG = {
    "gemini_api_key": "",
    "groq_api_key": "",
    "permission_tier": "write-no-exec",
    "dry_run": False,
    "default_model": "auto",
    "share_server": "https://neurocli-share.onrender.com",
    "theme": "cyberpunk",
}

PERMISSION_TIERS = {
    "read-only":      {"read": True,  "write": False, "exec": False},
    "write-no-exec":  {"read": True,  "write": True,  "exec": False},
    "full-auto":      {"read": True,  "write": True,  "exec": True},
}


def ensure_dirs():
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    SNAPSHOTS_DIR.mkdir(parents=True, exist_ok=True)


def load_config() -> dict:
    ensure_dirs()
    if CONFIG_FILE.exists():
        try:
            with open(CONFIG_FILE) as f:
                data = json.load(f)
            merged = {**DEFAULT_CONFIG, **data}
            # also check env vars as override
            if os.environ.get("GEMINI_API_KEY"):
                merged["gemini_api_key"] = os.environ["GEMINI_API_KEY"]
            if os.environ.get("GROQ_API_KEY"):
                merged["groq_api_key"] = os.environ["GROQ_API_KEY"]
            return merged
        except Exception:
            pass

    # fallback: check env vars even if no config file
    cfg = dict(DEFAULT_CONFIG)
    if os.environ.get("GEMINI_API_KEY"):
        cfg["gemini_api_key"] = os.environ["GEMINI_API_KEY"]
    if os.environ.get("GROQ_API_KEY"):
        cfg["groq_api_key"] = os.environ["GROQ_API_KEY"]
    return cfg


def save_config(cfg: dict):
    ensure_dirs()
    with open(CONFIG_FILE, "w") as f:
        json.dump(cfg, f, indent=2)


def get_permission(cfg: dict, action: str) -> bool:
    tier = cfg.get("permission_tier", "write-no-exec")
    return PERMISSION_TIERS.get(tier, PERMISSION_TIERS["write-no-exec"]).get(action, False)


def get_config_path() -> str:
    """Return config file path — useful for debugging."""
    return str(CONFIG_FILE)
