"""
Optimus Research Center - Mission ORC-31 Version Normalization & Safety Certification Test Suite
Validates:
1. Normalization of Application Version (1.1.0) differentiated from Portable Packager Utility Version (1.0.0-m22d)
   and External Integration Contract Protocol Version (1.0.0) across metadata, adapters, /health, and telemetry.
2. Safe R^2 metric handling with < 2 samples (no UndefinedMetricWarning or NaN) and >= 2 samples (valid R^2).
3. Intentionally active security blocks (NEEDS_MODEL external connection isolation, SANDBOX_UNAVAILABLE untrusted code block).
4. ORC31_CANDIDATE_MANIFEST.json SHA-256 integrity.
"""

import json
import hashlib
import warnings
from pathlib import Path
import numpy as np
import pytest
from sklearn.exceptions import UndefinedMetricWarning
from fastapi.testclient import TestClient

import app
from app.config import settings
from app.main import app as fastapi_app
from app.core.database import SessionLocal, init_db
from app.core.system_monitor import get_system_telemetry
from app.core.lab_adapters import AlgorithmLabAdapter, AILabAdapter
from app.core.sandbox import ExecutionPolicy, SandboxUnavailableError
from app.lab_algorithms.algorithms.predictive import (
    RidgePredictor,
    GradientBoostingPredictor,
    KNNPredictor,
)

BASE_DIR = Path(__file__).resolve().parent.parent


def compute_sha256(file_path: Path) -> str:
    h = hashlib.sha256()
    with open(file_path, "rb") as f:
        while chunk := f.read(65536):
            h.update(chunk)
    return h.hexdigest().lower()


def test_orc31_version_normalization_and_differentiation():
    """
    Verifies Application Version (1.1.0) is normalized across visible identifiers
    and explicitly differentiated from Packager Version (1.0.0-m22d) and Protocol Version (1.0.0).
    """
    assert app.__version__ == "1.1.0"
    assert app.__packager_version__ == "1.0.0-m22d"
    assert app.__protocol_version__ == "1.0.0"

    assert settings.VERSION == "1.1.0"
    assert settings.PACKAGER_VERSION == "1.0.0-m22d"
    assert settings.PROTOCOL_VERSION == "1.0.0"

    init_db()
    db = SessionLocal()
    try:
        algo_adapter = AlgorithmLabAdapter(db)
        ai_adapter = AILabAdapter(db)
        assert algo_adapter.get_capabilities().version == "1.1.0"
        assert ai_adapter.get_capabilities().version == "1.1.0"

        telemetry = get_system_telemetry()
        assert telemetry["application_version"] == "1.1.0"
        assert telemetry["packager_version"] == "1.0.0-m22d"
        assert "V1.1" in telemetry["digital_optimus_integration"]
    finally:
        db.close()

    client = TestClient(fastapi_app)
    resp = client.get("/health")
    assert resp.status_code == 200
    data = resp.json()
    assert data["status"] == "HEALTHY"
    assert data["version"] == "1.1.0"
    assert data["packager_version"] == "1.0.0-m22d"
    assert data["protocol_version"] == "1.0.0"
    assert data["titan_connected"] is False
    assert data["neurolab_connected"] is False
    assert data["digital_optimus_connected"] is False


def test_orc31_safe_r2_no_undefined_metric_warning():
    """
    Verifies predictive models do not emit UndefinedMetricWarning when evaluated on < 2 samples
    and return a well-defined R^2 score when evaluated on >= 2 samples.
    """
    X_train = np.array([[1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0], [5.0, 6.0]])
    y_train = np.array([3.0, 5.0, 7.0, 9.0, 11.0])
    X_test_single = np.array([[6.0, 7.0]])
    y_test_single = np.array([13.0])
    X_test_multi = np.array([[6.0, 7.0], [7.0, 8.0]])
    y_test_multi = np.array([13.0, 15.0])

    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always", UndefinedMetricWarning)
        for model_cls in (RidgePredictor, GradientBoostingPredictor, KNNPredictor):
            res_single = model_cls().train_and_eval(X_train, y_train, X_test_single, y_test_single)
            assert res_single["r2"] is None
            assert res_single["r2_status"] == "UNDEFINED_LESS_THAN_2_SAMPLES"

            res_multi = model_cls().train_and_eval(X_train, y_train, X_test_multi, y_test_multi)
            assert res_multi["r2"] is not None
            assert res_multi["r2_status"] == "DEFINED"

    r2_warnings = [w for w in caught if issubclass(w.category, UndefinedMetricWarning)]
    assert len(r2_warnings) == 0


def test_orc31_security_blocks_remain_enforced():
    """
    Verifies external connections remain disabled and untrusted experimental code execution remains blocked.
    """
    assert settings.TITAN_ENABLED is False
    assert settings.NEUROLAB_ENABLED is False
    assert settings.DIGITAL_OPTIMUS_ENABLED is False

    res = ExecutionPolicy.execute_untrusted_code("x = 1 + 1")
    assert res["status"] == "SANDBOX_UNAVAILABLE"
    assert res["candidate_status"] == "PENDING_SAFE_ENVIRONMENT"

    with pytest.raises(SandboxUnavailableError, match="SANDBOX_UNAVAILABLE"):
        ExecutionPolicy.execute_untrusted_code("x = 1 + 1", raise_exception=True)


def test_orc31_candidate_manifest_integrity():
    """Verifies ORC31_CANDIDATE_MANIFEST.json exists and matches all tracked files."""
    manifest_file = BASE_DIR / "ORC31_CANDIDATE_MANIFEST.json"
    assert manifest_file.is_file(), "ORC31_CANDIDATE_MANIFEST.json must exist in candidate root"
    manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
    assert manifest.get("mission") == "ORC-31"
    assert manifest.get("version") == "1.1.0"
    assert manifest.get("packager_version") == "1.0.0-m22d"
    assert manifest.get("protocol_version") == "1.0.0"
    tracked = manifest.get("core_and_modified_files_sha256", {})
    assert len(tracked) >= 25
    for rel_path, expected_sha in tracked.items():
        fp = BASE_DIR / rel_path
        assert fp.is_file(), f"Tracked file in ORC31_CANDIDATE_MANIFEST.json missing: {rel_path}"
        actual_sha = compute_sha256(fp)
        assert actual_sha == expected_sha.lower(), f"Hash mismatch for {rel_path}: expected {expected_sha}, got {actual_sha}"
