"""``apiprobe doctor`` — self-check.

Verifies the install is sane: version reads, all 18 default checks
load, the auth flows + factories + transport import. Useful as a CI
smoke step that doesn't hit the network.
"""

from __future__ import annotations


def handle_doctor() -> int:
    """Run the self-check and print results.

    Returns 0 on success, non-zero on any check failure.
    """
    print("apiprobe doctor")
    print()

    failures: list[str] = []

    # Version.
    try:
        from mgf.apiprobe import __version__

        print(f"  version           {__version__}")
    except Exception as exc:
        failures.append(f"version import failed: {exc}")
        print(f"  version           FAILED ({exc})")

    # mgf-common dep.
    try:
        from mgf.common import __version__ as common_version

        print(f"  mgf-common        {common_version}")
    except Exception as exc:
        failures.append(f"mgf-common import failed: {exc}")
        print(f"  mgf-common        FAILED ({exc})")

    # Checks.
    try:
        from mgf.apiprobe.checks import DEFAULT_CHECKS

        print(f"  default checks    {len(DEFAULT_CHECKS)}")
    except Exception as exc:
        failures.append(f"checks import failed: {exc}")
        print(f"  default checks    FAILED ({exc})")

    # Auth flows.
    try:
        from mgf.apiprobe.auth import (  # noqa: F401
            ApiKeyAuth,
            BasicAuth,
            BearerAuth,
            CookieAuth,
            CustomAuth,
        )

        print("  auth flows        5 (bearer, basic, api-key, cookie, custom)")
    except Exception as exc:
        failures.append(f"auth import failed: {exc}")
        print(f"  auth flows        FAILED ({exc})")

    # Transport.
    try:
        from mgf.apiprobe.transport import HttpxTransport  # noqa: F401

        print("  transport         HttpxTransport")
    except Exception as exc:
        failures.append(f"transport import failed: {exc}")
        print(f"  transport         FAILED ({exc})")

    # Factories.
    try:
        from mgf.apiprobe import factories

        # Smoke each factory.
        factories.uuid()
        factories.iso8601_z()
        factories.iban()
        factories.imei()
        factories.e164()
        print("  factories         5 (uuid, iso8601_z, iban, imei, e164)")
    except Exception as exc:
        failures.append(f"factories smoke failed: {exc}")
        print(f"  factories         FAILED ({exc})")

    print()
    if failures:
        print(f"DOCTOR: {len(failures)} failure(s).")
        return 1
    print("DOCTOR: ok.")
    return 0


__all__ = ["handle_doctor"]
