"""AXM-Audit CLI entry point — Code quality auditing tool.

Usage::

    axm-audit audit .
    axm-audit audit --json
    axm-audit audit --category lint
    axm-audit test . --mode=compact
    axm-audit version
"""

from __future__ import annotations

import json
import sys
from pathlib import Path
from typing import Annotated

import cyclopts

from axm_audit.core.rules.base import PERFECT_SCORE
from axm_audit.formatters import format_agent, format_json, format_report

__all__ = ["app"]

app = cyclopts.App(
    name="axm-audit",
    help="AXM Audit — Python code quality auditing tool.",
)


@app.command()
def audit(
    path: Annotated[
        str,
        cyclopts.Parameter(help="Path to project to audit"),
    ] = ".",
    *,
    json_output: Annotated[
        bool,
        cyclopts.Parameter(name=["--json"], help="Output as JSON"),
    ] = False,
    agent: Annotated[
        bool,
        cyclopts.Parameter(name=["--agent"], help="Compact agent-friendly output"),
    ] = False,
    category: Annotated[
        str | None,
        cyclopts.Parameter(name=["--category", "-c"], help="Filter to one category"),
    ] = None,
) -> None:
    """Audit a project's code quality against the AXM standard."""
    from axm_audit.core.auditor import audit_project

    project_path = Path(path).resolve()
    if not project_path.is_dir():
        print(f"❌ Not a directory: {project_path}", file=sys.stderr)
        raise SystemExit(1)

    result = audit_project(project_path, category=category)

    if agent:
        print(json.dumps(format_agent(result), indent=2))
    elif json_output:
        print(json.dumps(format_json(result), indent=2))
    else:
        print(format_report(result))

    if result.quality_score is not None and result.quality_score < PERFECT_SCORE:
        raise SystemExit(1)


@app.command()
def test(
    path: Annotated[
        str,
        cyclopts.Parameter(help="Path to project to test"),
    ] = ".",
    *,
    mode: Annotated[
        str,
        cyclopts.Parameter(
            name=["--mode"],
            help="Output mode: compact, failures, delta, targeted",
        ),
    ] = "failures",
    files: Annotated[
        list[str] | None,
        cyclopts.Parameter(
            name=["--files"],
            help="Specific test files to run",
        ),
    ] = None,
    markers: Annotated[
        list[str] | None,
        cyclopts.Parameter(
            name=["-m", "--markers"],
            help="Pytest markers to filter",
        ),
    ] = None,
    stop_on_first: Annotated[
        bool,
        cyclopts.Parameter(
            name=["-x", "--stop-on-first"],
            help="Stop on first failure",
        ),
    ] = True,
    agent: Annotated[
        bool,
        cyclopts.Parameter(name=["--agent"], help="Alias for --mode=compact"),
    ] = False,
) -> None:
    """Run tests with agent-optimized structured output."""
    import dataclasses

    from axm_audit.core.test_runner import run_tests

    project_path = Path(path).resolve()
    if not project_path.is_dir():
        print(f"❌ Not a directory: {project_path}", file=sys.stderr)
        raise SystemExit(1)

    effective_mode = "compact" if agent else mode
    report = run_tests(
        project_path,
        mode=effective_mode,  # type: ignore[arg-type]
        files=files,
        markers=markers,
        stop_on_first=stop_on_first,
    )

    print(json.dumps(dataclasses.asdict(report), indent=2))

    if report.failed > 0 or report.errors > 0:
        raise SystemExit(1)


@app.command()
def version() -> None:
    """Show axm-audit version."""
    from axm_audit import __version__

    print(f"axm-audit {__version__}")


def main() -> None:
    """Main entry point."""
    app()


if __name__ == "__main__":
    main()
