"""
Bounty reporter — LLM-generated bug bounty submission report.
"""

from __future__ import annotations

from pathlib import Path

from senshi.ai.brain import Brain
from senshi.ai.report_writer import ReportWriter
from senshi.reporters.models import ScanResult
from senshi.utils.logger import get_logger

logger = get_logger("senshi.reporters.bounty_report")


def generate_bounty_report(
    result: ScanResult,
    brain: Brain,
    platform: str = "",
    output_path: str | None = None,
) -> str:
    """
    Generate an LLM-written bounty submission report.

    Args:
        result: Complete scan results.
        brain: Brain instance for LLM report generation.
        platform: Bug bounty platform (msrc, hackerone, bugcrowd).
        output_path: Optional path to write the report.

    Returns:
        Markdown-formatted bounty report.
    """
    writer = ReportWriter(brain)
    sections: list[str] = []

    sections.append("# Bug Bounty Submission Report\n")
    sections.append(f"**Target:** {result.target}")
    sections.append(f"**Platform:** {platform or 'General'}")
    sections.append(f"**Generated by:** Senshi v{result.provider}\n")
    sections.append("---\n")

    # Generate individual finding reports
    for i, finding in enumerate(result.findings, 1):
        try:
            report = writer.write_finding_report(
                finding=finding,
                target=result.target,
                platform=platform,
            )
            sections.append(f"## Finding {i}\n")
            sections.append(report)
            sections.append("\n---\n")
        except Exception as e:
            logger.warning(f"Failed to generate report for finding {i}: {e}")
            sections.append(f"## Finding {i}: {finding.title}\n")
            sections.append(f"*Report generation failed: {e}*\n")

    # Generate executive summary
    if result.findings:
        try:
            summary = writer.write_scan_summary(
                findings=result.findings,
                chains=result.chains,
                target=result.target,
            )
            sections.insert(3, f"\n## Executive Summary\n\n{summary}\n")
        except Exception as e:
            logger.warning(f"Summary generation failed: {e}")

    report = "\n".join(sections)

    if output_path:
        Path(output_path).write_text(report, encoding="utf-8")
        logger.info(f"Bounty report saved to {output_path}")

    return report
