"""P1-1 Progressive Disclosure 테스트."""

import sys
import json
from unittest.mock import patch

# workspace root를 sys.path에 추가
sys.path.insert(0, "/home/jay/workspace")

from prompts.team_prompts import build_prompt, TOKEN_LIMITS, _count_tokens


SAMPLE_TASK_ID = "task-test-pd-01"
SAMPLE_TASK_DESC = "테스트용 작업 설명입니다. Progressive Disclosure 기능을 검증합니다. " * 20

# feature_flags를 true로 설정하는 헬퍼
def _enable_pd_flag(tmp_path):
    """임시 feature_flags.json 생성 + 환경변수 설정."""
    flags_file = tmp_path / ".claude" / "feature_flags.json"
    flags_file.parent.mkdir(parents=True, exist_ok=True)
    data = {
        "schema_version": "1.0",
        "updated_at": "2026-04-07T00:00:00+09:00",
        "flags": {
            "progressive_disclosure_enabled": True,
            "rw_isolation_enabled": False,
            "hooks_enforcement_enabled": False,
            "trust5_tagging_enabled": False,
            "model_map_enabled": False,
            "haiku_ab_enabled": False,
        },
    }
    flags_file.write_text(json.dumps(data, indent=2), encoding="utf-8")
    return str(flags_file)


def _disable_pd_flag(tmp_path):
    """임시 feature_flags.json 생성 (모두 false)."""
    flags_file = tmp_path / ".claude" / "feature_flags.json"
    flags_file.parent.mkdir(parents=True, exist_ok=True)
    data = {
        "schema_version": "1.0",
        "updated_at": "2026-04-07T00:00:00+09:00",
        "flags": {
            "progressive_disclosure_enabled": False,
            "rw_isolation_enabled": False,
            "hooks_enforcement_enabled": False,
            "trust5_tagging_enabled": False,
            "model_map_enabled": False,
            "haiku_ab_enabled": False,
        },
    }
    flags_file.write_text(json.dumps(data, indent=2), encoding="utf-8")
    return str(flags_file)


# TC-PD-01: summary phase 토큰 비율 검증
def test_summary_phase_token_ratio(tmp_path):
    flags_path = _enable_pd_flag(tmp_path)
    with patch("utils.feature_flags.FeatureFlagLoader.__init__", lambda self, path=None: (
        setattr(self, "_path", flags_path),
        setattr(self, "_cache", {}),
        setattr(self, "_mtime", 0.0),
        self._load(),
    )[-1]):
        full_prompt = build_prompt(
            "dev1-team", SAMPLE_TASK_ID, SAMPLE_TASK_DESC, disclosure_phase="full"
        )
        summary_prompt = build_prompt(
            "dev1-team", SAMPLE_TASK_ID + "-s", SAMPLE_TASK_DESC, disclosure_phase="summary"
        )
    full_tokens = _count_tokens(full_prompt)
    summary_tokens = _count_tokens(summary_prompt)
    # full이 summary limit(600)보다 충분히 클 때만 ratio 검증
    if full_tokens > TOKEN_LIMITS["summary"]:
        ratio = summary_tokens / full_tokens
        assert ratio <= 0.30, f"summary ratio {ratio:.2f} exceeds 0.30"
    else:
        # full이 이미 limit 이하이면 summary도 동일 → 비율 검증 불필요
        assert summary_tokens <= full_tokens + 10, "summary should not exceed full when full is already within limit"


# TC-PD-02: summary phase 절대 토큰 한도
def test_summary_phase_token_limit(tmp_path):
    flags_path = _enable_pd_flag(tmp_path)
    with patch("utils.feature_flags.FeatureFlagLoader.__init__", lambda self, path=None: (
        setattr(self, "_path", flags_path),
        setattr(self, "_cache", {}),
        setattr(self, "_mtime", 0.0),
        self._load(),
    )[-1]):
        prompt = build_prompt(
            "dev1-team", SAMPLE_TASK_ID + "-lim", SAMPLE_TASK_DESC, disclosure_phase="summary"
        )
    tokens = _count_tokens(prompt)
    assert tokens <= 600, f"summary tokens {tokens} exceeds 600 limit"


# TC-PD-03: CRITICAL 셋 포함 확인
def test_critical_set_always_included(tmp_path):
    flags_path = _enable_pd_flag(tmp_path)
    with patch("utils.feature_flags.FeatureFlagLoader.__init__", lambda self, path=None: (
        setattr(self, "_path", flags_path),
        setattr(self, "_cache", {}),
        setattr(self, "_mtime", 0.0),
        self._load(),
    )[-1]):
        for phase in ["summary", "standard", "full"]:
            prompt = build_prompt(
                "dev1-team", f"{SAMPLE_TASK_ID}-{phase}", SAMPLE_TASK_DESC, disclosure_phase=phase
            )
            assert "금지행위" in prompt, f"'금지행위' not in {phase} prompt"
            assert "QC 의무" in prompt, f"'QC 의무' not in {phase} prompt"
            assert "보고 형식" in prompt, f"'보고 형식' not in {phase} prompt"


# TC-PD-04: 플래그 비활성화 시 기존 동작 유지
def test_flag_disabled_fallback(tmp_path):
    flags_path = _disable_pd_flag(tmp_path)
    with patch("utils.feature_flags.FeatureFlagLoader.__init__", lambda self, path=None: (
        setattr(self, "_path", flags_path),
        setattr(self, "_cache", {}),
        setattr(self, "_mtime", 0.0),
        self._load(),
    )[-1]):
        full_prompt = build_prompt(
            "dev1-team", SAMPLE_TASK_ID + "-f1", SAMPLE_TASK_DESC, disclosure_phase="full"
        )
        summary_prompt = build_prompt(
            "dev1-team", SAMPLE_TASK_ID + "-f2", SAMPLE_TASK_DESC, disclosure_phase="summary"
        )
    # 플래그 비활성화 시 summary도 full과 동일 (disclosure 미적용)
    assert _count_tokens(full_prompt) == _count_tokens(summary_prompt), \
        "Flag disabled: summary should be same as full"
