"""SDK configuration and API client setup."""

import os
from dataclasses import dataclass
from pathlib import Path

_TOKEN_FILE = Path.home() / ".velar" / "token"


def _read_token_file() -> str:
    """Read API key from ~/.velar/token if it exists."""
    try:
        return _TOKEN_FILE.read_text().strip()
    except (OSError, IOError):
        return ""


def save_token(api_key: str) -> None:
    """Persist an API key to ~/.velar/token."""
    _TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
    _TOKEN_FILE.write_text(api_key)
    _TOKEN_FILE.chmod(0o600)


@dataclass
class Config:
    api_url: str
    api_key: str
    registry_url: str
    invoke_url: str

    @classmethod
    def from_env(cls) -> "Config":
        api_url = os.environ.get("VELAR_API_URL", "https://api.velar.run")
        registry_url = os.environ.get("VELAR_REGISTRY_URL", "registry.velar.run")
        invoke_url = os.environ.get("VELAR_INVOKE_URL", "https://invoke.velar.run")
        api_key = os.environ.get("VELAR_API_KEY", "") or _read_token_file()
        if not api_key:
            raise ValueError(
                "Not authenticated. Run 'velar login' to authenticate, "
                "or set the VELAR_API_KEY environment variable."
            )
        return cls(api_url=api_url, api_key=api_key, registry_url=registry_url, invoke_url=invoke_url)
