from __future__ import annotations

import json
from pathlib import Path

from cirtusai import credentials


def test_credentials_path(monkeypatch, tmp_path: Path) -> None:
    monkeypatch.setattr(Path, "home", lambda: tmp_path)
    path = credentials.get_credentials_path()
    assert str(path).endswith(".cirtus/credentials.json")


def test_save_and_load_credentials(monkeypatch, tmp_path: Path) -> None:
    monkeypatch.setattr(Path, "home", lambda: tmp_path)
    credentials.save_credentials("key", "https://api", "agent")
    loaded = credentials.load_credentials()
    assert loaded == {"api_key": "key", "base_url": "https://api", "agent_name": "agent"}

    creds_path = credentials.get_credentials_path()
    assert creds_path.exists()
    assert oct(creds_path.stat().st_mode & 0o777) == "0o600"


def test_load_invalid_json(monkeypatch, tmp_path: Path) -> None:
    monkeypatch.setattr(Path, "home", lambda: tmp_path)
    creds_path = credentials.get_credentials_path()
    creds_path.parent.mkdir(parents=True, exist_ok=True)
    creds_path.write_text("not-json")
    assert credentials.load_credentials() is None


def test_clear_credentials(monkeypatch, tmp_path: Path) -> None:
    monkeypatch.setattr(Path, "home", lambda: tmp_path)
    credentials.save_credentials("key", "https://api", "agent")
    assert credentials.get_credentials_path().exists()
    credentials.clear_credentials()
    assert not credentials.get_credentials_path().exists()
