from __future__ import annotations

from typing import Any, Dict

from rich.console import Console
from rich.table import Table

from ..discovery import DiscoveryResult
from ..scoring import ScoreBreakdown


def render_text_report(report: Dict[str, Any], discovery: DiscoveryResult, scores: ScoreBreakdown) -> str:
    console = Console(record=True)

    console.rule(f"CRA Readiness Scanner v{report['meta']['scannerVersion']}")

    console.print(f"[bold]Project:[/bold] {report['meta']['projectPath']}")

    # SBOM section
    console.print("\n[bold]SBOM Readiness[/bold]")
    if not discovery.sbom_found:
        console.print("No SBOM detected.")
    else:
        table = Table(show_header=True, header_style="bold")
        table.add_column("Path")
        table.add_column("Format")
        table.add_column("Components", justify="right")
        for f in discovery.sbom_files:
            table.add_row(str(f.path), f.format, str(f.component_count))
        console.print(table)

    # Practices section
    console.print("\n[bold]Vulnerability Handling Practices[/bold]")
    console.print(f"SECURITY.md present: {'yes' if discovery.has_security_md else 'no'}")
    console.print(f"Dependabot configured: {'yes' if discovery.has_dependabot else 'no'}")
    console.print(f"Docs include security section: {'yes' if discovery.has_docs_security_section else 'no'}")

    # Scores
    console.print("\n[bold]CRA Readiness Score[/bold]")
    console.print(f"Overall: [bold]{scores.overall}/100[/bold]")
    console.print(f"SBOM: {scores.sbom_score}/40")
    console.print(f"Vulnerabilities: {scores.vuln_score}/30")
    console.print(f"Practices: {scores.practices_score}/30")

    if scores.recommendations:
        console.print("\n[bold]Top Recommendations[/bold]")
        for rec in scores.recommendations:
            console.print(f"- [bold]{rec['title']}[/bold]: {rec['description']} ({rec['craReference']})")

    console.rule()

    return console.export_text()

