"""Post documentation sync suggestions to GitHub PR."""

from __future__ import annotations

import json
import subprocess
from typing import Any

from scripts.doc_sync.apply_rules import DocSyncIssue

# Severity level configuration
SEVERITY_CONFIG = {
    'error': {'emoji': '🔴', 'label': 'Error'},
    'warning': {'emoji': '🟡', 'label': 'Warning'},
    'info': {'emoji': '🔵', 'label': 'Info'},
}


class SuggestionFormatter:
    """Format documentation sync issues as GitHub suggestions."""

    def format_suggestion(
        self,
        severity: str,
        rule: str,
        description: str,
        suggestion_code: str,
    ) -> str:
        """Format a single suggestion for GitHub review comment.

        Args:
            severity: Severity level (error, warning, info).
            rule: Rule name that triggered the issue.
            description: Human-readable description of the issue.
            suggestion_code: Code to suggest as replacement.

        Returns:
            Formatted markdown string for GitHub comment.
        """
        config = SEVERITY_CONFIG.get(severity, SEVERITY_CONFIG['info'])
        emoji = config['emoji']
        label = config['label']

        return f"""{emoji} **{label}: {rule}**

{description}

```suggestion
{suggestion_code}
```"""


class ReviewGenerator:
    """Generate GitHub review comments from documentation sync issues."""

    def __init__(self) -> None:
        """Initialize the review generator."""
        self.formatter = SuggestionFormatter()

    def generate_review(self, issues: list[DocSyncIssue]) -> dict[str, Any]:
        """Generate review JSON with all issues.

        Args:
            issues: List of documentation sync issues.

        Returns:
            Dictionary with reviews array for GitHub API.
        """
        reviews = []

        for issue in issues:
            body = self.formatter.format_suggestion(
                severity=issue.severity,
                rule=issue.rule,
                description=issue.description,
                suggestion_code=issue.suggestion,
            )

            reviews.append({
                'path': issue.doc_file,
                'line': issue.line,
                'side': 'RIGHT',
                'severity': issue.severity,
                'rule': issue.rule,
                'body': body,
            })

        return {'reviews': reviews}

    def generate_summary(self, issues: list[DocSyncIssue]) -> str:
        """Generate summary markdown for PR comment.

        Args:
            issues: List of documentation sync issues.

        Returns:
            Markdown summary string.
        """
        counts = {'error': 0, 'warning': 0, 'info': 0}
        for issue in issues:
            if issue.severity in counts:
                counts[issue.severity] += 1

        return f"""## 📚 Documentation Sync Review

| Level | Count |
|-------|-------|
| 🔴 Error | {counts['error']} |
| 🟡 Warning | {counts['warning']} |
| 🔵 Info | {counts['info']} |

각 항목에서 **Apply suggestion** 버튼을 클릭하여 바로 수정을 적용할 수 있습니다.
"""


def post_review_to_pr(
    review_file: str,
    pr_number: int,
    repo: str | None = None,
) -> None:
    """Post review comments to GitHub PR.

    Args:
        review_file: Path to review JSON file.
        pr_number: Pull request number.
        repo: Repository in owner/repo format. Defaults to GITHUB_REPOSITORY env.
    """
    with open(review_file) as f:
        review = json.load(f)

    issues = []
    for item in review.get('reviews', []):
        issues.append(
            DocSyncIssue(
                rule=item.get('rule', ''),
                severity=item.get('severity', 'info'),
                code_file='',
                doc_file=item.get('path', ''),
                element_name='',
                description='',
                suggestion='',
                line=item.get('line', 0),
            )
        )

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

    # Post summary comment
    cmd = ['gh', 'pr', 'comment', str(pr_number), '--body', summary]
    subprocess.run(cmd, check=True)

    # Post individual review comments
    repo_param = repo or '${GITHUB_REPOSITORY}'
    for item in review.get('reviews', []):
        cmd = [
            'gh',
            'api',
            f'repos/{repo_param}/pulls/{pr_number}/comments',
            '-f',
            f'body={item["body"]}',
            '-f',
            f'path={item["path"]}',
            '-f',
            f'line={item["line"]}',
            '-f',
            'side=RIGHT',
        ]
        subprocess.run(cmd, check=True)


def main() -> None:
    """Main entry point for CLI usage."""
    import argparse

    parser = argparse.ArgumentParser(description='Post documentation sync suggestions to GitHub PR')
    parser.add_argument(
        '--review',
        required=True,
        help='Path to review JSON file',
    )
    parser.add_argument(
        '--pr',
        type=int,
        required=True,
        help='Pull request number',
    )
    parser.add_argument(
        '--repo',
        help='Repository in owner/repo format',
    )

    args = parser.parse_args()
    post_review_to_pr(args.review, args.pr, args.repo)


if __name__ == '__main__':
    main()
