"""tests/test_content_sanitizer.py — content_sanitizer.sanitize_output TDD 테스트."""

from __future__ import annotations

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

import pytest
from engine_v2.content_sanitizer import sanitize_output


class TestSanitizeOutput:
    """sanitize_output() — 봇 출력 필터링 검증."""

    def test_normal_text_passes_through(self) -> None:
        """일반 텍스트는 그대로 통과해야 한다."""
        text = "안녕하세요, Claude입니다. 도움이 필요하시면 말씀하세요."
        assert sanitize_output(text) == text

    def test_filters_claude_md_header(self) -> None:
        """CLAUDE.md 시스템 프롬프트 헤더 패턴을 필터링해야 한다."""
        text = "# 오딘 - 개발2팀장\n\n## 정체성\n당신은 오딘입니다.\n\n실제 응답 텍스트입니다."
        result = sanitize_output(text)
        assert "오딘 - 개발2팀장" not in result
        assert "## 정체성" not in result
        assert "실제 응답 텍스트입니다" in result

    def test_filters_system_prompt_sections(self) -> None:
        """시스템 프롬프트 섹션 헤더(## 역할, ## 작업 규칙 등)를 필터링해야 한다."""
        text = "## 역할\n백엔드 개발자입니다.\n## 작업 규칙\n코드를 작성하세요.\n\n실제 답변입니다."
        result = sanitize_output(text)
        assert "## 역할" not in result
        assert "## 작업 규칙" not in result
        assert "실제 답변입니다" in result

    def test_filters_tool_execution_code_blocks(self) -> None:
        """tool 실행 내용이 포함된 코드 블록을 필터링해야 한다."""
        text = "답변입니다.\n\n```shell\ncat /home/jay/CLAUDE.md\n```\n\n이후 답변입니다."
        result = sanitize_output(text)
        assert "cat /home/jay/CLAUDE.md" not in result
        assert "답변입니다" in result
        assert "이후 답변입니다" in result

    def test_filters_long_code_dumps(self) -> None:
        """20줄 이상의 연속 코드 블록(파일 덤프)을 필터링해야 한다."""
        code_lines = "\n".join([f"line {i}: some code content" for i in range(25)])
        text = f"답변입니다.\n\n```\n{code_lines}\n```\n\n결론입니다."
        result = sanitize_output(text)
        assert "line 0: some code content" not in result
        assert "line 24: some code content" not in result
        assert "답변입니다" in result
        assert "결론입니다" in result

    def test_preserves_short_code_blocks(self) -> None:
        """짧은 코드 블록(19줄 이하)은 보존해야 한다."""
        code = "def hello():\n    return 'world'"
        text = f"예시 코드입니다:\n\n```python\n{code}\n```\n\n이렇게 사용하세요."
        result = sanitize_output(text)
        assert "def hello():" in result
        assert "return 'world'" in result

    def test_empty_string_returns_empty(self) -> None:
        """빈 문자열 입력 시 빈 문자열을 반환해야 한다."""
        assert sanitize_output("") == ""

    def test_filtered_result_not_empty(self) -> None:
        """필터링 후 결과가 빈 문자열이면 원본을 반환해야 한다 (빈 응답 방지)."""
        text = "## 역할\n개발자입니다."
        result = sanitize_output(text)
        assert len(result) > 0

    def test_filters_read_grep_tool_patterns(self) -> None:
        """Read, Grep, Glob 등 tool 이름 패턴이 포함된 실행 블록을 필터링해야 한다."""
        text = "답변입니다.\n\n```\nRead file: /home/jay/workspace/CLAUDE.md\n     1→# Content here\n     2→More content\n```\n\n결론입니다."
        result = sanitize_output(text)
        assert "Read file:" not in result
        assert "결론입니다" in result

    def test_logging_debug_output(self) -> None:
        """필터링 전/후 길이 차이를 DEBUG 레벨로 로깅해야 한다."""
        import logging

        # 로깅은 구현에서 확인 - 이 테스트는 로깅이 있으면 통과
        text = "## 역할\n내용\n실제 답변"
        result = sanitize_output(text)
        assert result  # 빈 문자열이 아님
