"""
datanaut.config — Global config stored in ~/.datanaut/config.json

Users set their API key once with:
    datanaut config --api-key sk-...

It is then available to all datanaut commands globally,
no .env file needed in every project.
"""

import json
import os
from pathlib import Path

# Config lives at ~/.datanaut/config.json
CONFIG_DIR  = Path.home() / ".datanaut"
CONFIG_FILE = CONFIG_DIR / "config.json"


def load_config() -> dict:
    """Load config from ~/.datanaut/config.json. Returns {} if not found."""
    if CONFIG_FILE.exists():
        try:
            return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
        except Exception:
            return {}
    return {}


def save_config(data: dict):
    """Save config dict to ~/.datanaut/config.json."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CONFIG_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")
    # Restrict permissions on Unix (no-op on Windows)
    try:
        CONFIG_FILE.chmod(0o600)
    except Exception:
        pass


def get_api_key() -> str | None:
    """
    Resolve OPENAI_API_KEY with this priority:
      1. Environment variable OPENAI_API_KEY  (highest — lets users override)
      2. ~/.datanaut/config.json              (set via `datanaut config --api-key`)
      3. .env file in current directory       (legacy fallback)
    """
    # 1. Env var
    key = os.getenv("OPENAI_API_KEY")
    if key:
        return key

    # 2. Global config file
    cfg = load_config()
    key = cfg.get("openai_api_key")
    if key:
        os.environ["OPENAI_API_KEY"] = key   # inject so OpenAI SDK picks it up
        return key

    # 3. .env fallback
    try:
        from dotenv import load_dotenv
        load_dotenv(Path.cwd() / ".env")
        key = os.getenv("OPENAI_API_KEY")
        if key:
            return key
    except ImportError:
        pass

    return None


def set_api_key(api_key: str):
    """Persist the API key to ~/.datanaut/config.json."""
    cfg = load_config()
    cfg["openai_api_key"] = api_key
    save_config(cfg)


def show_config():
    """Print current config status."""
    G  = "\033[92m"
    Y  = "\033[93m"
    R  = "\033[31m"
    C  = "\033[36m"
    D  = "\033[2m"
    RS = "\033[0m"

    cfg = load_config()
    key = get_api_key()

    print(f"\n  {C}Datanaut config{RS}  {D}({CONFIG_FILE}){RS}\n")

    if key:
        masked = key[:8] + "..." + key[-4:] if len(key) > 12 else "****"
        source = "env var" if os.getenv("OPENAI_API_KEY") == key else "config file"
        print(f"  {G}✔{RS}  OPENAI_API_KEY  =  {masked}  {D}(from {source}){RS}")
    else:
        print(f"  {R}✖{RS}  OPENAI_API_KEY  =  not set")
        print(f"     Run: {C}datanaut config --api-key sk-...{RS}")

    print()