"""Entrypoint executed under sudo/root to finalize Cloudflare tunnel setup."""

from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
from typing import Optional

from .cloudflare_setup import ensure_tunnel_with_credentials
from .ensure_cloudflared import ensure_cloudflared_installed
from .state import credentials_path_for_tunnel


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Finish Cloudflare tunnel setup as root.")
    parser.add_argument(
        "--mode",
        choices=["setup", "install-only"],
        default="setup",
        help="Whether to install cloudflared only or perform the full tunnel setup.",
    )
    parser.add_argument("--tunnel-name", help="Name of the Cloudflare named tunnel.")
    parser.add_argument(
        "--config-path",
        type=Path,
        help="Path where the tunnel configuration should be written.",
    )
    parser.add_argument(
        "--origincert-path",
        type=Path,
        help="Path to the Cloudflare origin certificate (cert.pem).",
    )
    return parser


def main() -> None:
    args = _build_parser().parse_args()
    if args.origincert_path:
        os.environ["TUNNEL_ORIGIN_CERT"] = str(args.origincert_path)
    cloudflared_version = ensure_cloudflared_installed()

    if args.mode == "install-only":
        print(json.dumps({"cloudflared_version": cloudflared_version}))
        return

    if not args.tunnel_name or not args.config_path:
        raise ValueError("tunnel-name and config-path are required for setup mode.")

    tunnel_info = ensure_tunnel_with_credentials(args.tunnel_name, config_path=args.config_path)
    credentials_file = credentials_path_for_tunnel(tunnel_info.tunnel_id)

    payload = {
        "tunnel_id": tunnel_info.tunnel_id,
        "tunnel_name": tunnel_info.name,
        "tunnel_existed": tunnel_info.existed,
        "credentials_file": str(credentials_file),
        "config_path": str(args.config_path),
        "cloudflared_version": cloudflared_version,
    }
    print(json.dumps(payload))


if __name__ == "__main__":
    main()


__all__ = ["main"]
