"""``cis490-bootstrap`` launcher.

Runs as root (needs CA private key access). Listens on 127.0.0.1:8446
behind Caddy's ``bootstrap.wg`` site — Caddy terminates TLS, this
service speaks plain HTTP on loopback only.
"""

from __future__ import annotations

import argparse
import logging
import sys
from pathlib import Path

import uvicorn

from bootstrap.app import make_app


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(prog="cis490-bootstrap")
    p.add_argument("--listen-host", default="127.0.0.1")
    p.add_argument("--listen-port", type=int, default=8446)
    p.add_argument(
        "--issuer-script",
        type=Path,
        default=Path("/home/max/.env/wg-pki/scripts/issue-cis490-client-cert.sh"),
        help="Path to the wg-pki leaf-cert mint script.",
    )
    p.add_argument(
        "--issued-root",
        type=Path,
        default=Path("/home/max/.env/wg-pki/issued"),
        help="Where minted tarballs are cached.",
    )
    p.add_argument("--log-level", default="info")
    args = p.parse_args(argv)

    logging.basicConfig(
        level=getattr(logging, args.log_level.upper(), logging.INFO),
        format="%(asctime)s %(levelname)s %(name)s %(message)s",
    )
    log = logging.getLogger("cis490.bootstrap.main")

    if not args.issuer_script.exists():
        log.error("issuer script missing: %s", args.issuer_script)
        return 2

    app = make_app(
        issuer_script=args.issuer_script,
        issued_root=args.issued_root,
    )
    log.info("listening on %s:%d", args.listen_host, args.listen_port)
    uvicorn.run(
        app,
        host=args.listen_host,
        port=args.listen_port,
        log_level=args.log_level,
        access_log=True,
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())
