from __future__ import annotations

import argparse
import subprocess
import sys
import time
import webbrowser
from typing import Any

try:
    from cf_cli.registry import register_command
except ImportError:  # pragma: no cover - optional dependency
    register_command = None


def _spawn_new_console(cmd: list[str]) -> subprocess.Popen:
    if sys.platform.startswith("win"):
        return subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_CONSOLE)
    return subprocess.Popen(cmd)


def _cmd_pipeline_report_serve(args: Any) -> int:
    cmd = [
        sys.executable,
        "-m",
        "cf_pipeline_report.server",
        args.manifest_or_dir,
    ]
    if args.duckdb:
        cmd += ["--duckdb", args.duckdb]
    if args.duckdb_dir:
        cmd += ["--duckdb-dir", args.duckdb_dir]
    if args.host:
        cmd += ["--host", args.host]
    if args.port:
        cmd += ["--port", str(args.port)]

    _spawn_new_console(cmd)
    time.sleep(0.6)
    url = f"http://{args.host}:{args.port}/"
    webbrowser.open(url)
    print(f"Opened report server in a new window: {url}")
    return 0


def _configure_serve_parser(parser: argparse.ArgumentParser) -> None:
    parser.add_argument("manifest_or_dir", help="Path to an RDF manifest file or a directory of manifests.")
    parser.add_argument("--duckdb", help="Path to a DuckDB database file (read-only).")
    parser.add_argument("--duckdb-dir", help="Directory containing per-pipeline DuckDB files.")
    parser.add_argument("--host", default="127.0.0.1", help="Host to bind (default: 127.0.0.1).")
    parser.add_argument("--port", type=int, default=8765, help="Port to bind (default: 8765).")
    parser.set_defaults(func=_cmd_pipeline_report_serve, _cf_handler=_cmd_pipeline_report_serve)


def _add_cf_serve_parser(subparsers: argparse._SubParsersAction) -> argparse.ArgumentParser:
    parser = subparsers.add_parser("report", help="Serve live pipeline reports.")
    _configure_serve_parser(parser)
    return parser


def _register_cf_cli() -> None:
    if register_command is None:
        return
    register_command(
        "pipeline",
        "report",
        _add_cf_serve_parser,
        group_help="Pipeline tools",
        command_help="Serve live pipeline reports",
    )


_register_cf_cli()
