"""Debug: trace the summary endpoint call"""
from fastapi.testclient import TestClient
from app import database as db_module
from app.database import Base
from tests.conftest import TEST_ENGINE, TEST_SESSION_LOCAL, create_test_user, get_token_for_user, auth_header, create_test_kpi
from app.main import app
from app.models import KPIAlert, KPIValue, KPIDefinition
from sqlalchemy import func
from sqlalchemy.orm import Session

# Track the session used in summary
_actual_sessions = []

def _get_db_override():
    """Debug version that captures the session"""
    s = TEST_SESSION_LOCAL()
    _actual_sessions.append(s)
    return s

# First test: test_summary_empty
print("=== Simulating test_summary_empty ===")
Base.metadata.create_all(bind=TEST_ENGINE)
app.dependency_overrides[db_module.get_db] = _get_db_override

session1 = TEST_SESSION_LOCAL()
create_test_user(session1)
# Note: login uses get_db which is overridden! But let's use create_test_user directly

# Hmm, the login also uses get_db. Let me bypass that.
# Actually let me create the user and generate a token manually
import hashlib
user = create_test_user(session1)

# Create a token directly
from app.auth_middleware import create_token
token = create_token(user.id)
headers = {"Authorization": f"Bearer {token}"}

client = TestClient(app)
resp = client.get("/api/cma/dashboard/summary", headers=headers)
print(f"  Status: {resp.status_code}")
print(f"  Data: {resp.json()}")

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

# Second test
print("=== Simulating test_summary_with_data ===")
Base.metadata.create_all(bind=TEST_ENGINE)
app.dependency_overrides[db_module.get_db] = _get_db_override

session2 = TEST_SESSION_LOCAL()
user2 = create_test_user(session2)
token2 = create_token(user2.id)

kpi = create_test_kpi(session2, kpi_code="F_REVENUE", dimension="finance")
kpi2 = create_test_kpi(session2, kpi_code="C_SATISFACTION", kpi_name="客户满意度", dimension="customer")

cnt_before = session2.query(func.count(KPIDefinition.id)).filter(KPIDefinition.status == "active").scalar()
print(f"  Direct count before calling endpoint: {cnt_before}")

alert = KPIAlert(kpi_id=kpi.id, alert_level="red", alert_message="营收预警", status="pending")
session2.add(alert)
session2.commit()

resp2 = client.get("/api/cma/dashboard/summary", headers={"Authorization": f"Bearer {token2}"})
print(f"  Status: {resp2.status_code}")
print(f"  Data: {resp2.json()}")

# Also check what the engine sees
conn = TEST_ENGINE.connect()
result = conn.execute(KPIDefinition.__table__.select())
rows = result.fetchall()
print(f"  Rows in KPIDefinition table via raw conn: {[(r.id, r.kpi_code, r.status) for r in rows]}")
conn.close()

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