from __future__ import annotations

from pathlib import Path
from typing import Optional

import click

from .scanner import ScanConfig, perform_scan


@click.group()
@click.version_option()
def cli() -> None:
    """CRA Readiness Scanner CLI."""


@cli.command("scan")
@click.argument("project_root", type=click.Path(path_type=Path), default=Path("."))
@click.option("--sbom", "sbom_path", type=click.Path(path_type=Path), help="Path to an SBOM file.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"], case_sensitive=False),
    default="text",
    show_default=True,
    help="Output format.",
)
@click.option(
    "--output",
    "output_path",
    type=click.Path(path_type=Path),
    help="Optional path to write JSON report.",
)
@click.option(
    "--min-score",
    "min_score",
    type=int,
    default=0,
    show_default=True,
    help="Minimum overall score (0-100). Exit with code 1 if below threshold.",
)
def scan_command(
    project_root: Path,
    sbom_path: Optional[Path],
    output_format: str,
    output_path: Optional[Path],
    min_score: int,
) -> None:
    """Run CRA readiness scan on a project."""
    config = ScanConfig(
        project_root=project_root,
        sbom_path=sbom_path,
        output_format=output_format,
        output_path=output_path,
    )
    score = perform_scan(config)
    if min_score > 0 and score < min_score:
        raise SystemExit(
            f"CRA readiness score ({score}) is below minimum threshold ({min_score})"
        )


def main() -> None:
    cli(prog_name="cra-scanner")

