"""CLI entry point for AttestMCP.

Commands:
  attestmcp serve   — Start the proxy server
  attestmcp verify  — Verify audit chain integrity
  attestmcp export  — Export audit records
"""

from __future__ import annotations

import argparse
import sys

from attestmcp import __version__


def cmd_serve(args: argparse.Namespace) -> None:
    """Start the AttestMCP proxy server."""
    import uvicorn

    from attestmcp.config import Settings
    from attestmcp.proxy import create_app

    settings = Settings()
    app = create_app(settings)
    uvicorn.run(
        app,
        host=settings.host,
        port=settings.port,
        log_level="info",
    )


def cmd_verify(args: argparse.Namespace) -> None:
    """Verify the integrity of the audit chain."""
    from attestmcp.config import Settings
    from attestmcp.store import SQLiteAuditStore

    settings = Settings()
    store = SQLiteAuditStore(db_path=settings.db_path)

    result = store.verify_chain()
    if result.valid:
        print(f"Chain intact. {result.records_checked} records verified.")
    else:
        print(f"CHAIN BROKEN at record {result.break_at_record_id}")
        print(f"  Expected hash: {result.expected_hash}")
        print(f"  Actual hash:   {result.actual_hash}")
        print(f"  Records checked before break: {result.records_checked}")
        sys.exit(1)


def cmd_export(args: argparse.Namespace) -> None:
    """Export audit records as JSON lines."""
    from datetime import UTC, datetime

    from attestmcp.config import Settings
    from attestmcp.store import SQLiteAuditStore

    settings = Settings()
    store = SQLiteAuditStore(db_path=settings.db_path)

    since = None
    if args.since:
        since = datetime.fromisoformat(args.since).replace(tzinfo=UTC)

    until = None
    if args.until:
        until = datetime.fromisoformat(args.until).replace(tzinfo=UTC)

    records = store.query(since=since, until=until, limit=args.limit)

    if args.output:
        with open(args.output, "w") as f:
            for record in records:
                f.write(record.model_dump_json() + "\n")
        print(f"Exported {len(records)} records to {args.output}")
    else:
        for record in records:
            print(record.model_dump_json())


def cmd_report(args: argparse.Namespace) -> None:
    """Generate an HTML compliance evidence report."""
    from datetime import UTC, datetime

    from attestmcp.config import Settings
    from attestmcp.report import generate_report
    from attestmcp.store import SQLiteAuditStore

    settings = Settings()
    store = SQLiteAuditStore(db_path=settings.db_path)

    since = None
    if args.since:
        since = datetime.fromisoformat(args.since).replace(tzinfo=UTC)

    until = None
    if args.until:
        until = datetime.fromisoformat(args.until).replace(tzinfo=UTC)

    html = generate_report(store, since=since, until=until)

    output = args.output or "attestmcp-evidence-report.html"
    with open(output, "w") as f:
        f.write(html)
    print(f"Evidence report written to {output}")


def main() -> None:
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        prog="attestmcp",
        description="Continuous compliance evidence for AI agent memory",
    )
    parser.add_argument(
        "--version", action="version", version=f"attestmcp {__version__}"
    )

    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # serve
    subparsers.add_parser("serve", help="Start the proxy server")

    # verify
    subparsers.add_parser("verify", help="Verify audit chain integrity")

    # export
    export_parser = subparsers.add_parser("export", help="Export audit records")
    export_parser.add_argument("--since", help="Start date (ISO 8601)")
    export_parser.add_argument("--until", help="End date (ISO 8601)")
    export_parser.add_argument(
        "--limit", type=int, default=10000, help="Max records to export"
    )
    export_parser.add_argument("--output", "-o", help="Output file path")

    # report
    report_parser = subparsers.add_parser(
        "report", help="Generate HTML compliance evidence report"
    )
    report_parser.add_argument("--since", help="Start date (ISO 8601)")
    report_parser.add_argument("--until", help="End date (ISO 8601)")
    report_parser.add_argument(
        "--output", "-o", help="Output file path (default: attestmcp-evidence-report.html)"
    )

    args = parser.parse_args()

    if args.command is None:
        parser.print_help()
        sys.exit(1)

    commands = {
        "serve": cmd_serve,
        "verify": cmd_verify,
        "export": cmd_export,
        "report": cmd_report,
    }
    commands[args.command](args)


if __name__ == "__main__":
    main()
