#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations

import argparse
import importlib
import sys
from pathlib import Path


def ok(label, value):
    print(f"[OK]   {label:28s} {value}")


def fail(label, value):
    print(f"[FAIL] {label:28s} {value}")


def main():
    p = argparse.ArgumentParser()
    p.add_argument(
        "--project_root",
        default="/root/disk_3tb/earlywarning/30072026",
    )
    p.add_argument(
        "--allow_missing_data",
        action="store_true",
    )
    p.add_argument(
        "--allow_missing_suite17",
        action="store_true",
    )
    p.add_argument(
        "--diagnostic_internal_backends",
        action="store_true",
    )
    args = p.parse_args()

    root = Path(args.project_root)
    errors = []

    print("=" * 100)
    print("SUITE19 FINAL ENVIRONMENT CHECK")
    print("=" * 100)
    print(f"python={sys.version}")
    print(f"executable={sys.executable}")

    for module in (
        "numpy",
        "pandas",
        "scipy",
        "sklearn",
        "joblib",
        "torch",
        "psutil",
    ):
        try:
            m = importlib.import_module(module)
            ok(
                module,
                getattr(
                    m,
                    "__version__",
                    "imported",
                ),
            )
        except Exception as exc:
            fail(module, repr(exc))
            errors.append(module)

    if not args.diagnostic_internal_backends:
        try:
            import tabm
            ok(
                "official TabM",
                getattr(
                    tabm,
                    "__version__",
                    "imported",
                ),
            )
        except Exception as exc:
            fail(
                "official TabM",
                repr(exc),
            )
            errors.append("tabm")

        try:
            rfm = importlib.import_module(
                "rfm"
            )

            if not hasattr(
                rfm,
                "LaplaceRFM",
            ):
                try:
                    sub = importlib.import_module(
                        "rfm.rfm"
                    )
                    LaplaceRFM = getattr(
                        sub,
                        "LaplaceRFM",
                    )
                except Exception:
                    raise ImportError(
                        "rfm imported but "
                        "LaplaceRFM unavailable"
                    )
            else:
                LaplaceRFM = (
                    rfm.LaplaceRFM
                )

            ok(
                "official LaplaceRFM",
                str(LaplaceRFM),
            )
        except Exception as exc:
            fail(
                "official LaplaceRFM",
                repr(exc),
            )
            errors.append("rfm")

    suite17 = root / "suite17"

    if (
        suite17
        / "suite17_pipeline.py"
    ).exists():
        ok(
            "Suite17",
            suite17,
        )
    elif not args.allow_missing_suite17:
        fail(
            "Suite17",
            suite17,
        )
        errors.append("suite17")

    data_paths = [
        root
        / "results"
        / "cross_faculty_residual_moe"
        / "cache",
        root
        / "results"
        / "suite12_structured_cache",
    ]

    if not args.allow_missing_data:
        for path in data_paths:
            if path.exists():
                ok(
                    path.name,
                    path,
                )
            else:
                fail(
                    path.name,
                    path,
                )
                errors.append(
                    str(path)
                )

    references = {
        "Suite14":
            root
            / "results"
            / "suite14_authority_safe_collaborative_moe",
        "Suite16":
            root
            / "results"
            / "suite16_conditional_tree_boosting",
        "Suite17":
            root
            / "results"
            / "suite17_robust_forward_specialist_boosting",
        "Suite18":
            root
            / "results"
            / "suite18_fmm_forward_specialist_boosting",
        "Council":
            root
            / "results"
            / "suite4"
            / "2_competence_council",
    }

    print("\n[REFERENCE ROOTS]")

    for name, path in references.items():
        print(
            f"  {name:10s} "
            f"{'FOUND' if path.exists() else 'MISSING'} "
            f"{path}"
        )

    if errors:
        print(
            "\n[FATAL] Suite19 final "
            "environment check failed:"
        )
        for e in errors:
            print(f"  - {e}")
        return 2

    print(
        "\n[PASS] Suite19 FINAL "
        "environment is ready."
    )

    return 0


if __name__ == "__main__":
    raise SystemExit(main())