"""
test_setup_auth.py - check_and_refresh_ttl 및 CLI --refresh 옵션 테스트

TDD: 테스트 먼저 작성 후 구현.
Firebase/Playwright 실제 호출 없음. mtime 조작과 파일 존재 여부만 테스트.
"""

import argparse
import os
import sys
import time

import pytest

sys.path.insert(0, "/home/jay/workspace/teams/shared")

from qc.auth import setup_auth


# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------

def _touch(path: str, age_seconds: float = 0.0) -> None:
    """파일을 생성하고 mtime을 현재 시각 - age_seconds 로 설정."""
    with open(path, "w", encoding="utf-8") as f:
        f.write("{}")
    now = time.time()
    past = now - age_seconds
    os.utime(path, (past, past))


# ---------------------------------------------------------------------------
# test cases
# ---------------------------------------------------------------------------

def test_check_ttl_fresh_file(tmp_path: pytest.TempPathFactory) -> None:
    """방금 생성된 storageState.json → 갱신 불필요 (False)."""
    p = str(tmp_path / "storageState.json")
    _touch(p, age_seconds=0)
    result = setup_auth.check_and_refresh_ttl(storage_state_path=p)
    assert result is False


def test_check_ttl_stale_file(tmp_path: pytest.TempPathFactory) -> None:
    """55분 전 mtime → 갱신 필요 (True)."""
    p = str(tmp_path / "storageState.json")
    _touch(p, age_seconds=55 * 60)
    result = setup_auth.check_and_refresh_ttl(storage_state_path=p)
    assert result is True


def test_check_ttl_missing_file(tmp_path: pytest.TempPathFactory) -> None:
    """파일 없음 → 갱신 필요 (True)."""
    p = str(tmp_path / "nonexistent_storageState.json")
    result = setup_auth.check_and_refresh_ttl(storage_state_path=p)
    assert result is True


def test_check_ttl_custom_max_age(tmp_path: pytest.TempPathFactory) -> None:
    """max_age_minutes=10 설정 시 15분 전 파일 → 갱신 필요 (True)."""
    p = str(tmp_path / "storageState.json")
    _touch(p, age_seconds=15 * 60)
    result = setup_auth.check_and_refresh_ttl(storage_state_path=p, max_age_minutes=10)
    assert result is True


def test_check_ttl_custom_max_age_still_valid(tmp_path: pytest.TempPathFactory) -> None:
    """max_age_minutes=10 설정 시 5분 전 파일 → 아직 유효 (False)."""
    p = str(tmp_path / "storageState.json")
    _touch(p, age_seconds=5 * 60)
    result = setup_auth.check_and_refresh_ttl(storage_state_path=p, max_age_minutes=10)
    assert result is False


def test_refresh_option_cli() -> None:
    """CLI에서 --refresh 옵션 파싱 확인."""
    parser = argparse.ArgumentParser()
    parser.add_argument("--refresh", action="store_true")
    args = parser.parse_args(["--refresh"])
    assert args.refresh is True

    args_no_refresh = parser.parse_args([])
    assert args_no_refresh.refresh is False
