import asyncio
from app.config import settings
from app.database import SessionLocal
from app.services import ai_service, vision_service

db = SessionLocal()
model, key = ai_service.get_model_for_task(db, "teach")
print(f"endpoint = {ai_service._endpoint()}")
print(f"model    = {model}\n")

# 1. real blocking completion
out = ai_service.chat(model=model, api_key=key, max_tokens=20,
                      messages=[{"role": "user", "content": "Reply with only the word: OK"}],
                      timeout=ai_service.DEFAULT_TIMEOUT)
print(f"1. chat()  -> {out!r}")

# 2. real async completion
out = asyncio.run(ai_service.achat(
    model=model, api_key=key, max_tokens=30, temperature=0.4,
    messages=[{"role": "user", "content": "Name the classic triad of nephrotic syndrome in under 12 words."}],
    timeout=ai_service.DEFAULT_TIMEOUT))
print(f"2. achat() -> {out!r}")

# 3. a real non-2xx: does it raise, with status and body?
try:
    ai_service.chat(model="model-that-does-not-exist", api_key=key, timeout=30,
                    messages=[{"role": "user", "content": "hi"}])
    print("3. ERROR: a bad model did not raise")
except ai_service.ProxyError as e:
    print(f"3. ProxyError status={e.status_code} probe_sees_4xx={400 <= e.status_code < 500}")
    print(f"   body -> {e.body[:180]!r}")

# 4. the vision probe, live, against a model the catalogue has no opinion on
vision_service._probes.clear()
vision_service._catalogue, vision_service._catalogue_at = {}, 0.0
cat = vision_service.catalogue()
print(f"\n4. catalogue read {len(cat)} models from the proxy")
print(f"   can_see({model!r}) = {vision_service.can_see(model, key)}")
unknown = [m for m, v in cat.items() if v is None]
if unknown:
    m = unknown[0]
    print(f"   probing {m!r} (catalogue says nothing) -> {vision_service._probe(m, None)}")
db.close()
