# Mock vendor API service for testing the vendor bridge.
# Simulates a third-party ML model API that returns metrics in JSON format.

from fastapi import FastAPI
from datetime import datetime, timezone
import random
import threading

app = FastAPI(
    title="Mock Vendor Sepsis Model API",
    description="Simulated vendor API for testing the MCA SDK vendor bridge pattern",
    version="1.0.0",
)

# Simulated state for realistic metric progression
_state = {
    "predictions_total": random.randint(10000, 15000),
    "errors_total": random.randint(50, 100),
    "last_poll_time": datetime.now(timezone.utc).timestamp(),
}
_state_lock = threading.Lock()


@app.get("/health")
def health_check():
    """Health check endpoint for container orchestration."""
    return {"status": "healthy", "service": "mock-vendor-api"}


@app.get("/metrics")
def get_metrics():
    """Return vendor-specific metrics in JSON format (non-OTLP).

    This simulates a vendor API that provides:
    - Model performance metrics (accuracy, f1_score)
    - Operational metrics (predictions, errors, latency)

    IMPORTANT: This vendor API returns DELTA values (increments since last poll),
    NOT cumulative totals. The bridge must convert these deltas to cumulative counters.

    Delta values are calculated based on time elapsed since last poll, simulating
    a realistic rate of predictions/errors per second.

    Example:
    - Poll 1: predictions_since_last_poll=42 → bridge cumulative=42
    - Poll 2: predictions_since_last_poll=35 → bridge cumulative=77 (42+35)
    """
    with _state_lock:
        current_time = datetime.now(timezone.utc).timestamp()
        time_elapsed = current_time - _state["last_poll_time"]

        # Simulate realistic prediction rate: ~1-2 predictions per second
        predictions_per_second = random.uniform(1.0, 2.0)
        predictions_delta = max(1, int(predictions_per_second * time_elapsed))

        # Simulate realistic error rate: ~0.01-0.05 errors per second
        errors_per_second = random.uniform(0.01, 0.05)
        errors_delta = int(errors_per_second * time_elapsed)

        # Update internal state for realism (tracking what we've sent)
        _state["predictions_total"] += predictions_delta
        _state["errors_total"] += errors_delta
        _state["last_poll_time"] = current_time

        response = {
            "model_id": "vendor-sepsis-v2",
            "model_version": "2.1.0",
            "vendor": "acme-healthcare-ai",
            "timestamp": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
            "metrics": {
                # Model performance metrics (gauges)
                "accuracy": round(random.uniform(0.85, 0.92), 4),
                "f1_score": round(random.uniform(0.80, 0.88), 4),
                # Operational metrics (DELTA VALUES - increments since last poll)
                "predictions_since_last_poll": predictions_delta,
                "errors_since_last_poll": errors_delta,
                # Latency percentile (gauge)
                "avg_latency_ms": random.randint(30, 60),
            },
        }

    return response


@app.get("/metrics/detailed")
def get_detailed_metrics():
    """Return detailed metrics including latency percentiles.

    Extended endpoint for more comprehensive monitoring.
    """
    base_metrics = get_metrics()
    base_metrics["metrics"].update(
        {
            "latency_p50_ms": random.randint(20, 35),
            "latency_p90_ms": random.randint(40, 55),
            "latency_p99_ms": random.randint(60, 100),
            "memory_usage_mb": random.randint(256, 512),
            "cpu_usage_percent": round(random.uniform(10, 30), 1),
        }
    )
    return base_metrics


@app.get("/model/info")
def get_model_info():
    """Return model metadata for resource attributes."""
    return {
        "model_id": "vendor-sepsis-v2",
        "model_version": "2.1.0",
        "vendor": "acme-healthcare-ai",
        "model_type": "classification",
        "description": "Early sepsis detection model",
        "last_trained": "2026-01-15T00:00:00Z",
        "features_count": 42,
    }


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8080)
