# ruff: noqa: E402

"""
Clinical Prediction Model - Non-instrumented Version

A baseline implementation without MCA SDK instrumentation for comparison.
Uses a real Random Forest model trained on Diabetes 130-US Hospitals dataset.
"""

import logging
import os
import sys
import time
import pickle
import pandas as pd

# Configure logging
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# Add both sdk-examples (for shared.py) and mca-prototype root (for mca_sdk) to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from shared import (
    print_gcp_auth_status,
    print_collector_status,
)


def load_model():
    """Load trained hospital readmission prediction model."""
    model_path = os.path.join(os.path.dirname(__file__), "readmission_model.pkl")

    if not os.path.exists(model_path):
        logger.error(f"Model not found at {model_path}")
        logger.error("Please run: python train_model.py")
        sys.exit(1)

    with open(model_path, "rb") as f:
        artifacts = pickle.load(f)

    return artifacts["model"], artifacts["scaler"], artifacts["feature_names"], artifacts["metrics"]


def main():
    logger.info("Clinical Prediction Model - Non-instrumented Version")

    # Load trained model
    logger.info("=== Loading Model ===")
    model, scaler, feature_names, metrics = load_model()
    logger.info(f"Model loaded (Accuracy: {metrics['accuracy']:.3f})")
    logger.info(f"Features: {len(feature_names)}")

    # Step 1-2: Verify prerequisites
    if not print_gcp_auth_status() or not print_collector_status():
        logger.warning("Prerequisites check failed (but continuing anyway for baseline)")

    logger.info("=== Model Initialization ===")
    logger.info("Model initialized (no instrumentation)")

    try:
        # Step 7: Input/Output Capture
        logger.info("=== Input/Output Capture ===")

        # Test with sample patient
        sample_encounter = {
            "encounter_id": "sanitized-enc-001",
            "patient_nbr": "sanitized-pat-001",
            "time_in_hospital": 7,
            "num_lab_procedures": 55,
            "num_procedures": 3,
            "num_medications": 18,
            "number_diagnoses": 9,
            "age_numeric": 75,
        }

        # Create DataFrame with proper feature names to match training
        feature_data = pd.DataFrame(
            [
                {
                    "time_in_hospital": sample_encounter.get("time_in_hospital", 5),
                    "num_lab_procedures": sample_encounter.get("num_lab_procedures", 40),
                    "num_procedures": sample_encounter.get("num_procedures", 2),
                    "num_medications": sample_encounter.get("num_medications", 15),
                    "number_diagnoses": sample_encounter.get("number_diagnoses", 7),
                    "age_numeric": sample_encounter.get("age_numeric", 65),
                }
            ],
            columns=feature_names,
        )
        features_scaled = scaler.transform(feature_data)
        prediction = model.predict(features_scaled)[0]
        probability = model.predict_proba(features_scaled)[0]

        result = {
            "prediction": "readmit_30_days" if prediction == 1 else "no_readmission",
            "risk_score": float(probability[1]),
            "confidence": float(max(probability)),
        }
        logger.info(
            f"Prediction: {result['prediction']} (risk: {result['risk_score']:.2f}, confidence: {result['confidence']:.2f})"
        )

        # Step 8: Manual predictions with threshold checking
        logger.info("=== Manual Predictions with Threshold Checking ===")
        latency_threshold_ms = 1000

        # Generate test encounters with varying characteristics
        test_encounters = [
            {
                "time_in_hospital": 3,
                "num_lab_procedures": 35,
                "num_procedures": 1,
                "num_medications": 10,
                "number_diagnoses": 5,
                "age_numeric": 55,
            },
            {
                "time_in_hospital": 10,
                "num_lab_procedures": 75,
                "num_procedures": 5,
                "num_medications": 25,
                "number_diagnoses": 12,
                "age_numeric": 82,
            },
            {
                "time_in_hospital": 5,
                "num_lab_procedures": 45,
                "num_procedures": 2,
                "num_medications": 15,
                "number_diagnoses": 7,
                "age_numeric": 48,
            },
        ]

        for i, encounter in enumerate(test_encounters):
            start_time = time.time()
            feature_data = pd.DataFrame([encounter], columns=feature_names)
            features_scaled = scaler.transform(feature_data)
            probability = model.predict_proba(features_scaled)[0]
            latency = time.time() - start_time

            prediction_id = f"pred-{i + 1:03d}"

            # Check threshold
            if latency * 1000 > latency_threshold_ms:
                logger.warning(
                    f"{prediction_id}: High latency {latency * 1000:.0f}ms (threshold: {latency_threshold_ms}ms)"
                )
            else:
                logger.info(f"{prediction_id}: {latency * 1000:.0f}ms (risk: {probability[1]:.2f})")

        # Step 9: Custom operation (Data Preprocessing)
        logger.info("=== Custom Operation (Data Preprocessing) ===")
        time.sleep(0.03)
        logger.info("Data preprocessing complete: records_processed=1000, features_extracted=42")

        # Step 10: Custom metrics
        logger.info("=== Custom Metrics ===")
        logger.info("Cache hits: 15 (cache_type=redis)")
        logger.info("Queue size: 8 (queue_name=predictions)")
        logger.info("Model confidence: 0.87")

        # Step 10b: Evaluation metrics
        logger.info("=== Evaluation Metrics ===")
        logger.info(f"Accuracy: {metrics['accuracy']:.3f} (dataset=validation)")
        logger.info(f"Precision: {metrics['precision']:.3f} (dataset=validation)")
        logger.info(f"Recall: {metrics['recall']:.3f} (dataset=validation)")

        # Step 11: Error tracking
        logger.info("=== Error Tracking ===")
        try:
            raise ValueError("Missing required feature: num_medications")
        except Exception as e:
            logger.error(
                f"Error recorded: {type(e).__name__} - {str(e)}",
                extra={
                    "encounter_id": "sanitized-enc-001",
                    "missing_features": ["num_medications"],
                },
            )

        # Step 12: Completion
        logger.info("=== Execution Complete ===")
        logger.info("✓ Telemetry sent to collector (auto-instrumented version)\n")

        # Step 13: Verification
        logger.info("=== Verify in GCP ===")
        logger.info("Cloud Logging: https://console.cloud.google.com/logs/query")
        logger.info('  Filter: logName="projects/bhsf-ai-team-projects/logs/emms-model-telemetry"')
        logger.info("\nCloud Trace: https://console.cloud.google.com/traces/list")
        logger.info("  Look for: predict, data_preprocessing spans")

    except Exception as e:
        logger.error(f"Error: {e}")
        raise


if __name__ == "__main__":
    main()
