"""Tests for doc-sync post_suggestions module."""

from __future__ import annotations

import json


class TestSuggestionFormatter:
    """Test suite for suggestion formatting."""

    def test_format_error_suggestion(self):
        """Format error-level suggestion with Korean description."""
        from scripts.doc_sync.post_suggestions import SuggestionFormatter

        formatter = SuggestionFormatter()
        result = formatter.format_suggestion(
            severity='error',
            rule='removed_api_reference',
            description='삭제된 `OldClass`가 문서에서 여전히 참조되고 있습니다.',
            suggestion_code='- `LocalExecutor` - 로컬 동기 실행\n- `RayExecutor` - Ray 기반 실행',
        )

        assert '🔴' in result
        assert 'Error' in result
        assert 'removed_api_reference' in result
        assert '```suggestion' in result
        assert '삭제된' in result  # Korean description

    def test_format_warning_suggestion(self):
        """Format warning-level suggestion."""
        from scripts.doc_sync.post_suggestions import SuggestionFormatter

        formatter = SuggestionFormatter()
        result = formatter.format_suggestion(
            severity='warning',
            rule='stale_signature',
            description='`execute` 메서드의 시그니처가 변경되었습니다.',
            suggestion_code='def execute(params: dict, timeout: int = 30) -> dict:\n    """Execute the action."""',
        )

        assert '🟡' in result
        assert 'Warning' in result
        assert '```suggestion' in result

    def test_format_info_suggestion(self):
        """Format info-level suggestion."""
        from scripts.doc_sync.post_suggestions import SuggestionFormatter

        formatter = SuggestionFormatter()
        result = formatter.format_suggestion(
            severity='info',
            rule='missing_parameter_doc',
            description='docstring에 `timeout` 파라미터 설명이 누락되었습니다.',
            suggestion_code='    timeout: Execution timeout in seconds.',
        )

        assert '🔵' in result
        assert 'Info' in result

    def test_suggestion_block_format(self):
        """Suggestion block should be properly formatted for GitHub."""
        from scripts.doc_sync.post_suggestions import SuggestionFormatter

        formatter = SuggestionFormatter()
        result = formatter.format_suggestion(
            severity='warning',
            rule='test_rule',
            description='Test',
            suggestion_code='new code here',
        )

        # GitHub suggestion block format
        assert '```suggestion\n' in result
        assert result.count('```') == 2  # Opening and closing


class TestReviewGenerator:
    """Test suite for review generation."""

    def test_generate_review_json(self):
        """Generate review JSON with correct structure."""
        from scripts.doc_sync.apply_rules import DocSyncIssue
        from scripts.doc_sync.post_suggestions import ReviewGenerator

        issues = [
            DocSyncIssue(
                rule='stale_signature',
                severity='warning',
                code_file='synapse_sdk/plugins/action.py',
                doc_file='docs/docs/plugins/index.md',
                element_name='execute',
                description='`execute` 함수 시그니처 변경',
                suggestion='시그니처 업데이트 필요',
                line=45,
            )
        ]

        generator = ReviewGenerator()
        review = generator.generate_review(issues)

        assert 'reviews' in review
        assert len(review['reviews']) == 1
        assert review['reviews'][0]['path'] == 'docs/docs/plugins/index.md'
        assert review['reviews'][0]['line'] == 45
        assert review['reviews'][0]['severity'] == 'warning'

    def test_generate_summary(self):
        """Generate summary with severity counts."""
        from scripts.doc_sync.apply_rules import DocSyncIssue
        from scripts.doc_sync.post_suggestions import ReviewGenerator

        issues = [
            DocSyncIssue(
                rule='r1',
                severity='error',
                code_file='',
                doc_file='test.md',
                element_name='',
                description='',
                suggestion='',
                line=0,
            ),
            DocSyncIssue(
                rule='r2',
                severity='warning',
                code_file='',
                doc_file='test.md',
                element_name='',
                description='',
                suggestion='',
                line=0,
            ),
            DocSyncIssue(
                rule='r3',
                severity='info',
                code_file='',
                doc_file='test.md',
                element_name='',
                description='',
                suggestion='',
                line=0,
            ),
        ]

        generator = ReviewGenerator()
        summary = generator.generate_summary(issues)

        assert '📚 Documentation Sync Review' in summary
        assert '🔴 Error' in summary
        assert '🟡 Warning' in summary
        assert '🔵 Info' in summary
        assert '| 1 |' in summary  # Each count is 1


class TestLanguagePolicy:
    """Test suite for language policy enforcement."""

    def test_korean_description_in_review(self):
        """Review descriptions should be in Korean."""
        from scripts.doc_sync.apply_rules import DocSyncIssue
        from scripts.doc_sync.post_suggestions import ReviewGenerator

        issues = [
            DocSyncIssue(
                rule='stale_signature',
                severity='warning',
                code_file='test.py',
                doc_file='test.md',
                element_name='execute',
                description='시그니처가 변경되었습니다.',
                suggestion='업데이트 필요',
                line=10,
            )
        ]

        generator = ReviewGenerator()
        review = generator.generate_review(issues)

        # Description should contain Korean
        body = review['reviews'][0]['body']
        assert '시그니처' in body or '변경' in body

    def test_english_code_in_suggestion(self):
        """Code suggestions for docstrings should be in English."""
        from scripts.doc_sync.post_suggestions import SuggestionFormatter

        formatter = SuggestionFormatter()

        # English docstring
        suggestion_code = '''def execute(params: dict, timeout: int = 30) -> dict:
    """Execute the action with timeout.

    Args:
        params: Action parameters.
        timeout: Timeout in seconds.

    Returns:
        Execution result.
    """'''

        result = formatter.format_suggestion(
            severity='warning',
            rule='stale_signature',
            description='시그니처 변경됨',  # Korean description
            suggestion_code=suggestion_code,
        )

        # English in code block
        assert 'Execute the action' in result
        assert 'Args:' in result


class TestGitHubAPIFormat:
    """Test suite for GitHub API compatibility."""

    def test_review_comment_structure(self):
        """Review comment should have correct GitHub API structure."""
        from scripts.doc_sync.apply_rules import DocSyncIssue
        from scripts.doc_sync.post_suggestions import ReviewGenerator

        issues = [
            DocSyncIssue(
                rule='test',
                severity='warning',
                code_file='test.py',
                doc_file='docs/test.md',
                element_name='func',
                description='Test',
                suggestion='Fix',
                line=42,
            )
        ]

        generator = ReviewGenerator()
        review = generator.generate_review(issues)

        comment = review['reviews'][0]
        # Required fields for GitHub API
        assert 'path' in comment
        assert 'line' in comment
        assert 'body' in comment
        assert 'side' in comment
        assert comment['side'] == 'RIGHT'

    def test_json_serializable(self):
        """Review output should be JSON serializable."""
        from scripts.doc_sync.apply_rules import DocSyncIssue
        from scripts.doc_sync.post_suggestions import ReviewGenerator

        issues = [
            DocSyncIssue(
                rule='test',
                severity='error',
                code_file='test.py',
                doc_file='docs/test.md',
                element_name='func',
                description='한글 설명',
                suggestion='Fix',
                line=10,
            )
        ]

        generator = ReviewGenerator()
        review = generator.generate_review(issues)

        # Should not raise
        json_str = json.dumps(review, ensure_ascii=False)
        parsed = json.loads(json_str)
        assert parsed == review
