import json
from termchat.config import CONFIG_DIR, CREDENTIALS_FILE


def save_tokens(access_token: str, refresh_token: str) -> None:
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CREDENTIALS_FILE.write_text(
        json.dumps(
            {"access_token": access_token, "refresh_token": refresh_token}
        )
    )


def load_tokens() -> tuple[str, str] | None:
    if not CREDENTIALS_FILE.exists():
        return None
    try:
        data = json.loads(CREDENTIALS_FILE.read_text())
        return data["access_token"], data["refresh_token"]
    except (json.JSONDecodeError, KeyError):
        return None


def clear_tokens() -> None:
    if CREDENTIALS_FILE.exists():
        CREDENTIALS_FILE.unlink()
