from src.vendor_state import get_vendor_state, VendorMetric

class _StubTT:
 def __init__(self, used=0, limit=0, cache_hits=0, cache_misses=0):
  self.used = used
  self.limit = limit
  self.cache_hits = cache_hits
  self.cache_misses = cache_misses

class _StubController:
 def __init__(self, token_tracker=None, last_error=None, vendor_quota=None):
  self.token_tracker = token_tracker
  self.last_error = last_error
  self.vendor_quota = vendor_quota if vendor_quota is not None else {}

class _StubApp:
 def __init__(self, controller):
  self.current_provider = "Anthropic"
  self.current_model = "claude-opus-4"
  self.controller = controller

def test_get_vendor_state_returns_core_metrics():
 ctrl = _StubController(token_tracker=_StubTT(used=78234, limit=200000, cache_hits=1200, cache_misses=80), vendor_quota={"remaining_pct": 87})
 app = _StubApp(ctrl)
 metrics = get_vendor_state(app)
 keys = {m.key for m in metrics}
 assert "provider_model" in keys
 assert "context_window" in keys
 assert "cache" in keys
 assert "quota" in keys
 assert "last_error" in keys

def test_missing_data_renders_em_dash_not_crash():
 ctrl = _StubController(token_tracker=None, last_error=None, vendor_quota={})
 app = _StubApp(ctrl)
 metrics = get_vendor_state(app)
 assert len(metrics) > 0
 for m in metrics:
  assert m.value is not None
  assert m.value != ""

def test_context_window_state_warn_above_75_percent():
 ctrl = _StubController(token_tracker=_StubTT(used=160000, limit=200000, cache_hits=0, cache_misses=0))
 app = _StubApp(ctrl)
 metrics = get_vendor_state(app)
 cw = next(m for m in metrics if m.key == "context_window")
 assert cw.state == "warn"
 assert "80%" in cw.value

def test_last_error_state_error_when_present():
 ctrl = _StubController(token_tracker=None, last_error={"class": "ProviderError", "message": "rate limit"})
 app = _StubApp(ctrl)
 metrics = get_vendor_state(app)
 err = next(m for m in metrics if m.key == "last_error")
 assert err.state == "error"
 assert "ProviderError" in err.value
