"""
Example: Model with External API Calls (Auto-instrumentable)
This file makes HTTP requests which will be automatically instrumented.
"""
import urllib3

import time
import random
import requests
import logging

# Set up standard Python logging - OpenTelemetry will automatically capture this!
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Disable SSL warnings for demo
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def fetch_patient_features(patient_id: str) -> dict:
    """Fetch patient features from external API (auto-instrumented)."""
    logger.info(f"Fetching features for patient: {patient_id}")
    requests.get(
        "https://httpbin.org/json",
        timeout=5,
        verify=False
    )
    time.sleep(0.1)
    return {
        "patient_id": patient_id,
        "age": random.randint(40, 90),
        "conditions": ["diabetes", "hypertension"]
    }

def call_ml_model_api(features: dict) -> dict:
    """Call external ML model API (auto-instrumented)."""
    logger.info("Calling external ML model API...")
    requests.post(
        "https://httpbin.org/post",
        json=features,
        timeout=5,
        verify=False
    )
    risk_score = random.uniform(0.1, 0.9)
    prediction = "high_risk" if risk_score > 0.7 else "low_risk"
    logger.info(f"Received prediction: {prediction} (score: {risk_score:.2f})")
    
    return {
        "prediction": prediction,
        "risk_score": risk_score,
        "confidence": 0.85
    }

def save_prediction_to_db(prediction: dict):
    """Simulate database write (would be auto-instrumented with DB library)."""
    logger.info("Saving prediction to database...")
    requests.post(
        "https://httpbin.org/post",
        json={"prediction": prediction},
        timeout=5,
        verify=False
    )
    logger.info("Prediction successfully saved.")

def main():
    logger.info("Starting auto-instrumented model pipeline...")

    try:
        patient_data = fetch_patient_features("patient-001")
        result = call_ml_model_api(patient_data)
        save_prediction_to_db(result)

        logger.info("Pipeline completed successfully!")

        # Give telemetry time to flush background batches over network
        time.sleep(5)

    except Exception as e:
        logger.error(f"Pipeline error: {e}", exc_info=True)
        raise

if __name__ == "__main__":
    main()
