# Copyright (c) 2026 MergeGuide, Inc. All rights reserved.
# SPDX-License-Identifier: Proprietary
"""PR comment formatting for Bitbucket.

Provides functions to format policy evaluation results as Bitbucket PR comments.
Uses Markdown formatting supported by Bitbucket.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from mergeguide.engine.reporter import EvaluationReport

# Marker to identify MergeGuide comments for updates
COMMENT_MARKER = "<!-- mergeguide-policy-check -->"


def format_pr_comment(report: EvaluationReport, dashboard_url: str | None = None) -> str:
    """Format evaluation results as a Bitbucket PR comment.

    Args:
        report: EvaluationReport with evaluation results
        dashboard_url: Optional URL to full report in dashboard

    Returns:
        Markdown-formatted comment string
    """
    lines = [COMMENT_MARKER, ""]

    # Header with status
    if report.summary.passed:
        lines.append("## :white_check_mark: MergeGuide Policy Check Passed")
    else:
        lines.append("## :x: MergeGuide Policy Check Failed")

    lines.append("")

    # Summary stats
    lines.append(f"**Files checked:** {report.summary.total_files}")
    lines.append(f"**Violations found:** {report.summary.total_violations}")

    if report.summary.total_violations > 0:
        lines.append("")
        lines.append("| Severity | Count |")
        lines.append("|----------|-------|")
        if report.summary.error_count > 0:
            lines.append(f"| :red_circle: Error | {report.summary.error_count} |")
        if report.summary.warning_count > 0:
            lines.append(f"| :yellow_circle: Warning | {report.summary.warning_count} |")
        if report.summary.info_count > 0:
            lines.append(f"| :blue_circle: Info | {report.summary.info_count} |")

    # Show violations (limited to first 10)
    if report.violations:
        lines.append("")
        lines.append("### Violations")
        lines.append("")

        for _i, violation in enumerate(report.violations[:10]):
            severity_icon = {
                "error": ":red_circle:",
                "warning": ":yellow_circle:",
                "info": ":blue_circle:",
            }.get(violation.severity, ":white_circle:")

            lines.append(
                f"- {severity_icon} **{violation.rule_name}** "
                f"in `{violation.file_path}:{violation.line_no}`"
            )
            lines.append(f"  > {violation.message}")
            if violation.remediation:
                lines.append(f"  > *Fix:* {violation.remediation}")
            lines.append("")

        if len(report.violations) > 10:
            remaining = len(report.violations) - 10
            lines.append(f"*...and {remaining} more violation(s)*")
            lines.append("")

    # Dashboard link
    if dashboard_url:
        lines.append("")
        lines.append(f"[View full report in MergeGuide Dashboard]({dashboard_url})")

    # Footer
    lines.append("")
    lines.append("---")
    lines.append("*Powered by [MergeGuide](https://mergeguide.dev)*")

    return "\n".join(lines)


def format_pending_comment() -> str:
    """Format a comment indicating check is in progress.

    Returns:
        Markdown comment string
    """
    return f"""{COMMENT_MARKER}

## :hourglass: MergeGuide Policy Check In Progress

Evaluating your changes against configured policies...

---
*Powered by [MergeGuide](https://mergeguide.dev)*
"""


def format_error_comment(error_message: str) -> str:
    """Format a comment indicating an error occurred.

    Args:
        error_message: Error description

    Returns:
        Markdown comment string
    """
    return f"""{COMMENT_MARKER}

## :warning: MergeGuide Policy Check Error

An error occurred while evaluating your changes:

```
{error_message}
```

Please try again or contact your administrator if the problem persists.

---
*Powered by [MergeGuide](https://mergeguide.dev)*
"""
