"""asa scan — ACI diagnostic. Ported from v1."""

import sys
from pathlib import Path

import typer

from ..core import logging as log


def run_scan(path: str, *, json_output: bool = False, no_url: bool = False) -> None:
    """Scan repository for structural risk — AI Chaos Index diagnostic."""
    from ..engine_loader import require_engine
    require_engine()
    from ..engine.scanner.scanner import RepoScanner
    from ..engine.scanner.formatter import format_terminal_output, format_json_output
    try:
        project_path = Path(path).resolve()
        if not project_path.is_dir():
            log.error(f"Not a directory: {project_path}")
            raise typer.Exit(1)

        scanner = RepoScanner()
        result = scanner.scan(project_path)

        if json_output:
            typer.echo(format_json_output(result))
        else:
            typer.echo(format_terminal_output(result, show_url=not no_url))

    except Exception as e:
        log.error(f"[INTERNAL ERROR] {e}")
        raise typer.Exit(2)
