from app import app, MonthlySummaryAnalysis
from database.manager import DatabaseManager
from sqlalchemy import func, case, desc

# Mocking the filter logic since it's an inner function
def apply_filters_debug(q, year=None, month=None, ignore_year=False):
    print(f"Applying filters: year={year}, ignore_year={ignore_year}")
    if year and not ignore_year: 
        print(" -> Filtering by year")
        q = q.filter(MonthlySummaryAnalysis.year == year)
    if month: 
        q = q.filter(MonthlySummaryAnalysis.month == month)
    return q

    db_manager = DatabaseManager()
    session = db_manager.get_session()
    year = 2025
    month = None # Simulating the curl request
    
    print("--- Debugging Div Dist Query ---")
    div_dist_q = session.query(
        MonthlySummaryAnalysis.division,
        func.sum(MonthlySummaryAnalysis.sales_amt_curr).label('sales'),
        func.sum(case((MonthlySummaryAnalysis.year == 2024, MonthlySummaryAnalysis.sales_amt_curr), else_=0)).label('sales_2024'),
        func.sum(case((MonthlySummaryAnalysis.year == 2025, MonthlySummaryAnalysis.sales_amt_curr), else_=0)).label('sales_2025')
    ).group_by(MonthlySummaryAnalysis.division).order_by(desc('sales')).limit(12)
    
    div_dist_q = apply_filters_debug(div_dist_q, year=year, ignore_year=True)
    
    print("SQL:", div_dist_q.statement.compile(compile_kwargs={"literal_binds": True}))
    results = div_dist_q.all()
    print(f"Results Count: {len(results)}")
    if results:
        print("First result:", results[0])

    print("\n--- Debugging Regular Filter (Comparison) ---")
    # What happens if we DO filter by year?
    div_dist_q_filtered = session.query(
        MonthlySummaryAnalysis.division,
        func.sum(MonthlySummaryAnalysis.sales_amt_curr).label('sales')
    ).group_by(MonthlySummaryAnalysis.division).order_by(desc('sales')).limit(12)
    div_dist_q_filtered = apply_filters_debug(div_dist_q_filtered, year=year, ignore_year=False)
    print(f"Filtered Results Count: {len(div_dist_q_filtered.all())}")
