"""
test_finish_task_lv4_audit.py — finish-task.sh L369~L444 Lv.4 보안 감사 검증 테스트
작성자: 벨레스 (QA 테스터)
태스크: task-2089
"""

import re
import os
from unittest.mock import patch

WORKSPACE_ROOT = "/home/jay/workspace"
FINISH_TASK_PATH = os.path.join(WORKSPACE_ROOT, "scripts", "finish-task.sh")


# ---------------------------------------------------------------------------
# 로직 재현 함수들 (finish-task.sh L371-L388 / L405-L421)
# ---------------------------------------------------------------------------

def is_lv4(task_file_content: str) -> bool:
    """finish-task.sh L371-L388의 Lv.4 판정 Python 로직 재현"""
    m = re.search(r'## 레벨\s*\n(.*?)(?=\n## |\Z)', task_file_content, re.DOTALL)
    if m:
        section = m.group(1).strip().lower()
        if 'critical' in section or 'security' in section or re.search(r'lv\.?4|level\s*4', section):
            return True
    return False


def check_loki_security(report_content: str) -> str:
    """finish-task.sh L405-L421의 로키 보안 감사 참여 기록 파싱 Python 로직 재현"""
    has_loki = bool(re.search(r'로키|Loki|loki', report_content))
    has_security = bool(re.search(r'보안 감사|security audit|레드팀|red.?team', report_content, re.IGNORECASE))
    if has_loki and has_security:
        return 'PASS'
    elif has_loki:
        return 'PARTIAL'
    else:
        return 'MISSING'


# ---------------------------------------------------------------------------
# is_lv4 테스트 케이스
# ---------------------------------------------------------------------------

def test_is_lv4_critical():
    """## 레벨 섹션에 'critical' → True"""
    content = "# task-2089\n\n## 레벨\n- critical\n\n## 작업 목록\n- 항목1\n"
    assert is_lv4(content) is True


def test_is_lv4_security():
    """## 레벨 섹션에 'security' → True"""
    content = "# task-2089\n\n## 레벨\n- security\n\n## 작업 목록\n- 항목1\n"
    assert is_lv4(content) is True


def test_is_lv4_lv_dot_4():
    """## 레벨 섹션에 'lv.4' → True"""
    content = "# task-2089\n\n## 레벨\n- lv.4\n\n## 작업 목록\n- 항목1\n"
    assert is_lv4(content) is True


def test_is_lv4_lv4_no_dot():
    """## 레벨 섹션에 'lv4' → True"""
    content = "# task-2089\n\n## 레벨\nlv4\n\n## 작업 목록\n- 항목1\n"
    assert is_lv4(content) is True


def test_is_lv4_level_4_with_space():
    """## 레벨 섹션에 'level 4' → True"""
    content = "# task-2089\n\n## 레벨\n- level 4\n\n## 작업 목록\n- 항목1\n"
    assert is_lv4(content) is True


def test_is_lv4_normal_returns_false():
    """## 레벨 섹션에 'normal' → False"""
    content = "# task-2089\n\n## 레벨\n- normal\n\n## 작업 목록\n- 항목1\n"
    assert is_lv4(content) is False


def test_is_lv4_lv3_returns_false():
    """## 레벨 섹션에 'lv.3' → False"""
    content = "# task-2089\n\n## 레벨\n- lv.3\n\n## 작업 목록\n- 항목1\n"
    assert is_lv4(content) is False


def test_is_lv4_no_level_section_returns_false():
    """## 레벨 섹션 없음 → False"""
    content = "# task-2089\n\n## 개요\n내용 없음\n\n## 작업 목록\n- 항목1\n"
    assert is_lv4(content) is False


# ---------------------------------------------------------------------------
# check_loki_security 테스트 케이스
# ---------------------------------------------------------------------------

def test_check_loki_security_korean_loki_and_security_audit():
    """로키 + 보안 감사 → PASS"""
    content = "로키가 보안 감사에 참여하였습니다."
    assert check_loki_security(content) == 'PASS'


def test_check_loki_security_korean_loki_only():
    """로키만 포함 → PARTIAL"""
    content = "로키가 작업을 완료하였습니다."
    assert check_loki_security(content) == 'PARTIAL'


def test_check_loki_security_missing():
    """로키 및 보안 감사 모두 없음 → MISSING"""
    content = "일반 작업 완료 보고서입니다."
    assert check_loki_security(content) == 'MISSING'


def test_check_loki_security_english_loki_and_security_audit():
    """Loki + security audit (영문) → PASS"""
    content = "Loki participated in the security audit."
    assert check_loki_security(content) == 'PASS'


def test_check_loki_security_korean_loki_and_redteam():
    """로키 + 레드팀 → PASS"""
    content = "로키가 레드팀 활동에 참여하였습니다."
    assert check_loki_security(content) == 'PASS'


def test_check_loki_security_lowercase_loki_and_red_team():
    """loki + red team → PASS"""
    content = "loki joined the red team exercise."
    assert check_loki_security(content) == 'PASS'


# ---------------------------------------------------------------------------
# security-audit 파일 존재 확인 (os.path.isfile mock)
# ---------------------------------------------------------------------------

def test_security_audit_file_exists_mock():
    """security-audit 파일 경로에 대해 os.path.isfile이 True를 반환하는지 mock으로 확인"""
    audit_file_path = os.path.join(WORKSPACE_ROOT, "reports", "security-audit.md")
    with patch("os.path.isfile", return_value=True) as mock_isfile:
        result = os.path.isfile(audit_file_path)
        mock_isfile.assert_called_once_with(audit_file_path)
        assert result is True


def test_security_audit_file_missing_mock():
    """security-audit 파일이 없을 때 os.path.isfile이 False를 반환하는지 mock으로 확인"""
    audit_file_path = os.path.join(WORKSPACE_ROOT, "reports", "security-audit.md")
    with patch("os.path.isfile", return_value=False) as mock_isfile:
        result = os.path.isfile(audit_file_path)
        mock_isfile.assert_called_once_with(audit_file_path)
        assert result is False
