"""task-1037.1: 디자인 작업 제한 규칙 테스트

team_prompts.py와 DIRECT-WORKFLOW.md에 추가된 디자인 금지 규칙을 검증합니다.
"""

import os
import re
from pathlib import Path

import pytest

_WORKSPACE = Path(os.environ.get("WORKSPACE_ROOT", "/home/jay/workspace"))


class TestTeamPromptsDesignRestriction:
    """team_prompts.py 디자인 제한 규칙 테스트."""

    @pytest.fixture
    def team_prompts_content(self) -> str:
        """team_prompts.py 파일 내용 로드."""
        path = _WORKSPACE / "prompts/team_prompts.py"
        return path.read_text(encoding="utf-8")

    def test_direct_prompt_has_design_restriction(self, team_prompts_content: str) -> None:
        """_build_direct_prompt에 디자인 금지 규칙이 있어야 함."""
        # "디자인 작업 직접 수행 금지" 문구가 있는지 확인
        assert (
            "디자인 작업 직접 수행 금지" in team_prompts_content
        ), "team_prompts.py에 '디자인 작업 직접 수행 금지' 규칙이 없음"

    def test_direct_prompt_mentions_design_team(self, team_prompts_content: str) -> None:
        """_build_direct_prompt에 디자인팀 호출 명시가 있어야 함."""
        assert "디자인팀 호출 필요" in team_prompts_content, "team_prompts.py에 '디자인팀 호출 필요' 문구가 없음"

    def test_direct_prompt_forbids_skills(self, team_prompts_content: str) -> None:
        """_build_direct_prompt에서 satori/gemini/hybrid 스킬 호출 금지 명시."""
        assert (
            "satori" in team_prompts_content and "gemini" in team_prompts_content and "hybrid" in team_prompts_content
        ), "team_prompts.py에 satori/gemini/hybrid 스킬 언급이 없음"

    def test_glm_prompt_has_design_restriction(self, team_prompts_content: str) -> None:
        """_build_glm_prompt에 디자인 금지 규칙이 있어야 함."""
        # _build_glm_prompt 함수 내에 디자인 금지 규칙이 있는지 확인
        # 함수가 정의된 부분을 찾아서 검사
        glm_prompt_match = re.search(r"def _build_glm_prompt.*?(?=def |\Z)", team_prompts_content, re.DOTALL)
        assert glm_prompt_match, "_build_glm_prompt 함수를 찾을 수 없음"
        glm_prompt_code = glm_prompt_match.group(0)
        assert (
            "디자인 작업 직접 수행 금지" in glm_prompt_code
        ), "_build_glm_prompt에 '디자인 작업 직접 수행 금지' 규칙이 없음"

    def test_import_works(self) -> None:
        """team_prompts.py가 정상적으로 import 되어야 함."""
        try:
            from prompts.team_prompts import TEAM_INFO, build_prompt

            assert True
        except Exception as e:
            pytest.fail(f"team_prompts.py import 실패: {e}")

    def test_build_prompt_generates_design_rule(self) -> None:
        """build_prompt() 호출 시 디자인 금지 규칙이 포함되어야 함."""
        from prompts.team_prompts import build_prompt

        # dev1-team으로 테스트
        prompt = build_prompt(
            team_id="dev1-team", task_id="test-123", task_desc="테스트 작업", level="normal", task_type="coding"
        )

        assert "디자인 작업 직접 수행 금지" in prompt, "생성된 프롬프트에 '디자인 작업 직접 수행 금지' 규칙이 없음"
        assert "디자인팀 호출 필요" in prompt, "생성된 프롬프트에 '디자인팀 호출 필요' 문구가 없음"

    def test_glm_prompt_generates_design_rule(self) -> None:
        """GLM 팀 프롬프트에도 디자인 금지 규칙이 포함되어야 함."""
        from prompts.team_prompts import build_prompt

        # dev8-team (GLM)으로 테스트
        prompt = build_prompt(
            team_id="dev8-team", task_id="test-456", task_desc="GLM 테스트 작업", level="normal", task_type="coding"
        )

        assert "디자인 작업 직접 수행 금지" in prompt, "GLM 프롬프트에 '디자인 작업 직접 수행 금지' 규칙이 없음"


class TestDirectWorkflowDesignRestriction:
    """DIRECT-WORKFLOW.md 디자인 제한 섹션 테스트."""

    @pytest.fixture
    def workflow_content(self) -> str:
        """DIRECT-WORKFLOW.md 파일 내용 로드."""
        path = _WORKSPACE / "prompts/DIRECT-WORKFLOW.md"
        return path.read_text(encoding="utf-8")

    def test_has_design_restriction_section(self, workflow_content: str) -> None:
        """디자인 제한 섹션이 있어야 함."""
        assert "디자인 작업 제한" in workflow_content, "DIRECT-WORKFLOW.md에 '디자인 작업 제한' 섹션이 없음"


class TestDesignTeamModel:
    """design-team.json 모델 설정 테스트."""

    @pytest.fixture
    def design_team_data(self) -> dict:
        """design-team.json 파일 로드."""
        import json

        path = _WORKSPACE / "memory/org-details/design-team.json"
        with open(path, encoding="utf-8") as f:
            return json.load(f)

    def test_venus_model_is_gemini(self, design_team_data: dict) -> None:
        """비너스 모델이 gemini여야 함."""
        venus = design_team_data.get("members_detail", {}).get("venus-delegate", {})
        model = venus.get("model", "")
        assert model == "gemini", f"비너스 모델이 'gemini'이 아님: {model}"

    def test_venus_engine_is_google(self, design_team_data: dict) -> None:
        """비너스 엔진이 google이어야 함."""
        venus = design_team_data.get("members_detail", {}).get("venus-delegate", {})
        engine = venus.get("engine", "")
        assert engine == "google", f"비너스 엔진이 'google'이 아님: {engine}"

    def test_design_team_structure_valid(self, design_team_data: dict) -> None:
        """design-team.json 구조가 유효해야 함."""
        required_keys = ["team_id", "team_name", "lead", "members_detail"]
        for key in required_keys:
            assert key in design_team_data, f"design-team.json에 필수 키 '{key}'가 없음"


class TestIntegration:
    """통합 테스트."""

    def test_no_syntax_errors(self) -> None:
        """수정된 파일들이 구문 에러 없이 로드되어야 함."""
        files_to_check = [
            str(_WORKSPACE / "prompts/team_prompts.py"),
            str(_WORKSPACE / "prompts/DIRECT-WORKFLOW.md"),
            str(_WORKSPACE / "memory/org-details/design-team.json"),
        ]

        for file_path in files_to_check:
            path = Path(file_path)
            assert path.exists(), f"파일이 존재하지 않음: {file_path}"

            # Python 파일은 import 테스트
            if file_path.endswith(".py"):
                try:
                    if file_path.endswith("team_prompts.py"):
                        from prompts.team_prompts import build_prompt
                except Exception as e:
                    pytest.fail(f"Python 파일 로드 실패 ({file_path}): {e}")

            # JSON 파일은 파싱 테스트
            elif file_path.endswith(".json"):
                import json

                try:
                    with open(path, encoding="utf-8") as f:
                        json.load(f)
                except json.JSONDecodeError as e:
                    pytest.fail(f"JSON 파싱 실패 ({file_path}): {e}")
