#!/usr/bin/env python3
"""Quick test to verify metrics export to file."""

import time
import os
from mca_sdk import MCAClient

# Paths
METRICS_FILE = "test-exports/otel-metrics.json"

# Ensure directory exists
os.makedirs("test-exports", exist_ok=True)

# Clear any existing file
if os.path.exists(METRICS_FILE):
    os.remove(METRICS_FILE)

print("Creating MCA client...")
client = MCAClient(
    service_name="manual-test",
    model_id="mdl-test-001",
    model_version="1.0.0",
    team_name="test-team",
    model_category="internal",
    model_type="regression",
    collector_endpoint="http://localhost:4318",
    buffering_enabled=False,
)

print("Sending 600 predictions to trigger batch size...")
for i in range(600):
    client.record_prediction(input_data={"id": i}, output={"prediction": i % 2}, latency=0.001)
    if (i + 1) % 100 == 0:
        print(f"  Sent {i + 1}/600 predictions")

print("\nDebug: Checking meter provider state...")
print(f"  Meter provider: {client._meter_provider}")
print(f"  Meter provider type: {type(client._meter_provider)}")
if hasattr(client._meter_provider, "_sdk_config"):
    print(f"  SDK config: {client._meter_provider._sdk_config}")
if hasattr(client._meter_provider, "_metric_readers"):
    print(f"  Metric readers: {client._meter_provider._metric_readers}")
    for reader in client._meter_provider._metric_readers:
        print(f"    Reader type: {type(reader)}")

print("\nExplicitly flushing metrics before shutdown...")
# Force flush to export any pending metrics
flush_result = client._meter_provider.force_flush(timeout_millis=10000)
print(f"Force flush result: {flush_result}")
print("Metrics flushed, waiting 5s for collector to receive...")
time.sleep(5)

print("Calling shutdown with 15s timeout...")
client.shutdown(timeout_millis=15000)

print("Waiting 10 more seconds for collector batch processor...")
time.sleep(10)

print(f"\nChecking for metrics file at {METRICS_FILE}...")
if os.path.exists(METRICS_FILE):
    size = os.path.getsize(METRICS_FILE)
    print(f"✓ File exists! Size: {size} bytes")
    if size > 0:
        print("\nFirst 500 characters:")
        with open(METRICS_FILE) as f:
            print(f.read(500))
else:
    print("✗ File does not exist!")
    print("\nChecking test-exports directory:")
    if os.path.exists("test-exports"):
        files = os.listdir("test-exports")
        if files:
            print(f"  Files found: {files}")
        else:
            print("  Directory is empty")
    else:
        print("  Directory does not exist")
