from __future__ import annotations

import argparse
import json
import sys

from .builtin_checks import disk_space_check, http_check, tcp_check
from .core import ServiceMonitor


def _add_tcp_checks(monitor: ServiceMonitor, values: list[str]) -> None:
    for value in values:
        name, address = value.split("=", 1)
        host, raw_port = address.rsplit(":", 1)
        monitor.add_check(name.strip(), tcp_check(host=host.strip(), port=int(raw_port.strip())))


def _add_http_checks(monitor: ServiceMonitor, values: list[str]) -> None:
    for value in values:
        name, url = value.split("=", 1)
        monitor.add_check(name.strip(), http_check(url=url.strip()))


def _add_disk_checks(monitor: ServiceMonitor, values: list[str]) -> None:
    for value in values:
        name, config = value.split("=", 1)
        path, raw_threshold = config.split(",", 1)
        monitor.add_check(
            name.strip(),
            disk_space_check(path=path.strip(), min_free_percent=float(raw_threshold.strip())),
        )


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Run dependency health checks for services")
    parser.add_argument(
        "--tcp",
        action="append",
        default=[],
        metavar="NAME=HOST:PORT",
        help="TCP check, for example: Database=127.0.0.1:5432",
    )
    parser.add_argument(
        "--http",
        action="append",
        default=[],
        metavar="NAME=URL",
        help="HTTP check, for example: External API=https://api.example.com/health",
    )
    parser.add_argument(
        "--disk",
        action="append",
        default=[],
        metavar="NAME=PATH,MIN_FREE_PERCENT",
        help="Disk check, for example: Disk Space=/,10",
    )
    parser.add_argument(
        "--timeout",
        type=float,
        default=3.0,
        help="Timeout in seconds used by network checks",
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="Print report in JSON format",
    )
    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()

    monitor = ServiceMonitor(timeout=args.timeout)

    try:
        _add_tcp_checks(monitor, args.tcp)
        _add_http_checks(monitor, args.http)
        _add_disk_checks(monitor, args.disk)
    except ValueError as exc:
        parser.error(f"Invalid check format: {exc}")

    report = monitor.run()

    if args.json:
        print(json.dumps(report.to_dict(), indent=2))
    else:
        print(report.to_table())

    return 0 if report.is_healthy else 1


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