"""Tests for autodebug/config.py — credentials storage and token management."""

from __future__ import annotations

import json
import os
import stat
from pathlib import Path
from unittest.mock import patch

import pytest

from autodebug.config import (
    CONFIG_DIR,
    CREDENTIALS_PATH,
    TOKEN_REFRESH_BUFFER,
)


@pytest.fixture
def temp_config(tmp_path, monkeypatch):
    """Redirect credential paths to temp directory."""
    creds_path = tmp_path / "credentials.json"
    monkeypatch.setattr("autodebug.config.CREDENTIALS_PATH", creds_path)
    monkeypatch.setattr("autodebug.config.CONFIG_DIR", tmp_path)
    return creds_path


def test_credentials_path_exists():
    """CREDENTIALS_PATH constant is defined and points to expected location."""
    assert CREDENTIALS_PATH.name == "credentials.json"
    assert ".hikaflow" in str(CREDENTIALS_PATH)


def test_config_dir_exists():
    """CONFIG_DIR constant is defined."""
    assert CONFIG_DIR.name == ".hikaflow"


def test_token_refresh_buffer():
    """TOKEN_REFRESH_BUFFER is reasonable (1-10 minutes)."""
    assert 60 <= TOKEN_REFRESH_BUFFER <= 600


def test_save_and_load_credentials(temp_config):
    """Round-trip save/load of credentials."""
    from autodebug.config import load_credentials, save_credentials

    creds = {"access_token": "test-token", "refresh_token": "refresh-123"}
    save_credentials(creds)
    loaded = load_credentials()
    assert loaded["access_token"] == "test-token"
    assert loaded["refresh_token"] == "refresh-123"


def test_save_credentials_creates_directory(tmp_path, monkeypatch):
    """save_credentials creates parent directory if missing."""
    from autodebug.config import save_credentials

    new_dir = tmp_path / "newdir"
    creds_path = new_dir / "credentials.json"
    monkeypatch.setattr("autodebug.config.CREDENTIALS_PATH", creds_path)
    monkeypatch.setattr("autodebug.config.CONFIG_DIR", new_dir)

    save_credentials({"access_token": "tok"})
    assert creds_path.exists()


def test_load_credentials_missing_file(temp_config):
    """load_credentials returns empty dict when file doesn't exist."""
    from autodebug.config import load_credentials

    result = load_credentials()
    assert result == {}
