"""Debug: trace DB state from within the endpoint"""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from sqlalchemy import func

from app import database as db_module
from app.database import Base
from tests.conftest import TEST_ENGINE, TEST_SESSION_LOCAL
from app.main import app

# Track summary route calls
original_summary = None
import app.api.dashboard as dashboard_mod

# Monkey-patch summary to debug
original_get_summary = dashboard_mod.get_dashboard_summary

def debug_summary(*args, **kwargs):
    # Get the db session
    from app.models import KPIDefinition
    db = kwargs.get('db')
    if db is None:
        for a in args:
            if isinstance(a, Session):
                db = a
                break
    if db:
        cnt = db.query(func.count(KPIDefinition.id)).filter(KPIDefinition.status == "active").scalar()
        all_k = db.query(KPIDefinition).all()
        print(f"[DEBUG SUMMARY] kpi_total query: {cnt}")
        print(f"[DEBUG SUMMARY] all KPIs in session: {[(k.id, k.kpi_code, k.status) for k in all_k]}")
        print(f"[DEBUG SUMMARY] session is {id(db)}")
    return original_get_summary(*args, **kwargs)

dashboard_mod.get_dashboard_summary = debug_summary

# Run the sequence
Base.metadata.create_all(bind=TEST_ENGINE)

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

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

print("=== First user (simulating test_summary_empty) ===")
create_test_user(session1)
client = TestClient(app)
token1 = get_token_for_user(client)
resp = client.get("/api/cma/dashboard/summary", headers=auth_header(token1))
print(f"Response: {resp.json()}")
print()

# Now simulate second test
print("=== Simulating second test (test_summary_with_data) ===")
# Drop and recreate tables like setup_db does
Base.metadata.drop_all(bind=TEST_ENGINE)
Base.metadata.create_all(bind=TEST_ENGINE)

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

user2 = create_test_user(session2)
# Use a fresh TestClient for login
from fastapi.testclient import TestClient as TC
client2 = TC(app)
token2 = get_token_for_user(client2)
kpi2a = create_test_kpi(session2, kpi_code="F_REVENUE", dimension="finance")
kpi2b = create_test_kpi(session2, kpi_code="C_SATISFACTION", kpi_name="客户满意度", dimension="customer")
print(f"Created KPIs: {kpi2a.id}, {kpi2b.id}")

cnt2 = session2.query(func.count(KPIDefinition.id)).filter(KPIDefinition.status == "active").scalar()
print(f"Direct count in session2: {cnt2}")

resp2 = client.get("/api/cma/dashboard/summary", headers=auth_header(token2))
print(f"Response: {resp2.json()}")

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