"""Local credential storage for the Specwright CLI.

Credentials are persisted at ``~/.config/specwright/credentials.json``
with file permissions restricted to the current user (0600).
"""

from __future__ import annotations

import json
import os
import time
from pathlib import Path

_CONFIG_DIR = Path.home() / ".config" / "specwright"
_CRED_FILE = _CONFIG_DIR / "credentials.json"


def load_credentials() -> dict | None:
    """Load saved credentials, or return None if absent / malformed."""
    try:
        return json.loads(_CRED_FILE.read_text())
    except (FileNotFoundError, json.JSONDecodeError, OSError):
        return None


def save_credentials(cred: dict) -> None:
    """Persist a credential dict to disk (chmod 0600)."""
    _CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    _CRED_FILE.write_text(json.dumps(cred, indent=2))
    os.chmod(_CRED_FILE, 0o600)


def clear_credentials() -> None:
    """Remove the credential file if it exists."""
    _CRED_FILE.unlink(missing_ok=True)


def is_token_expired(cred: dict) -> bool:
    """Check whether the access token in *cred* has expired.

    Returns True if ``expires_at`` is in the past (with a 30-second buffer)
    or if the field is missing.
    """
    expires_at = cred.get("expires_at")
    if expires_at is None:
        return True
    return time.time() >= (expires_at - 30)
