"""Debug test_dashboard failures"""
from fastapi.testclient import TestClient
from app.main import app
from app.database import get_db
from tests.conftest import TEST_ENGINE, TEST_SESSION_LOCAL, Base
from sqlalchemy.orm import Session
from sqlalchemy import func

# Create tables
Base.metadata.create_all(bind=TEST_ENGINE)

session = TEST_SESSION_LOCAL()
app.dependency_overrides[get_db] = lambda: session

from tests.conftest import create_test_user, get_token_for_user, auth_header, create_test_kpi
from app.models import KPIAlert, KPIValue, KPIDefinition

user = create_test_user(session)
token = get_token_for_user(TestClient(app))
print(f"Token: {token[:20]}...")

# Create KPIs
kpi = create_test_kpi(session, kpi_code='F_REVENUE', dimension='finance')
kpi2 = create_test_kpi(session, kpi_code='C_SATISFACTION', kpi_name='客户满意度', dimension='customer')

print(f"Created KPI1 id={kpi.id}, KPI2 id={kpi2.id}")

# Check count directly
cnt = session.query(func.count(KPIDefinition.id)).filter(KPIDefinition.status == "active").scalar()
print(f"Direct count: {cnt}")

all_kpis = session.query(KPIDefinition).all()
print(f"All KPIs: {[(k.id, k.kpi_code, k.status) for k in all_kpis]}")

# Call summary
client = TestClient(app)
resp = client.get("/api/cma/dashboard/summary", headers=auth_header(token))
print(f"Summary status: {resp.status_code}")
print(f"Summary data: {resp.json()}")

# Test KPIs endpoint
alert = KPIAlert(kpi_id=kpi.id, alert_level="red", alert_message="营收预警", status="pending")
session.add(alert)
session.commit()

# Create KPIValue for kpis test
kpi_val = KPIValue(kpi_id=kpi.id, period="2026-06", actual_value=85.0)
session.add(kpi_val)
session.commit()

resp2 = client.get("/api/cma/dashboard/kpis", headers=auth_header(token))
print(f"KPIs status: {resp2.status_code}")
print(f"KPIs data: {resp2.json()}")

app.dependency_overrides.clear()
Base.metadata.drop_all(bind=TEST_ENGINE)
