#!/usr/bin/env python3
"""Test if the trial-balance API fix is applied"""
import requests
import json

url = 'http://127.0.0.1:18080/trial-balance'
params = {
    'fiscal_year': 2025,
    'date_from': '2025-06-01',
    'date_to': '2025-12-31'
}

print("🔍 Testing API...")
print(f"URL: {url}")
print(f"Params: {params}")
print()

try:
    response = requests.get(url, params=params)
    response.raise_for_status()
    data = response.json()
    
    # Check if data is a dict or list
    print(f"Response type: {type(data)}")
    
    if isinstance(data, dict):
        print("Response is a dict, checking structure...")
        print(json.dumps(data, indent=2, ensure_ascii=False)[:500])
        
        # Check if it has a data key
        if 'data' in data:
            data = data['data']
        else:
            print("\nDict keys:", list(data.keys())[:5])
    
    if isinstance(data, list):
        print(f"Response is a list with {len(data)} items")
        
        # Find the target row
        target = [row for row in data if isinstance(row, dict) and row.get('account_name') == '繰越利益剰余金合計']
        
        if target:
            row = target[0]
            print("\n✓ Found: 繰越利益剰余金合計")
            print(f"  debit:  {row.get('debit')}")
            print(f"  credit: {row.get('credit')}")
            print()
            print("Expected (after fix):")
            print("  debit:  0")
            print("  credit: 7967855")
            print()
            
            debit_correct = row.get('debit') == '0'
            credit_correct = row.get('credit') == '7967855'
            
            if debit_correct and credit_correct:
                print("✓✓✓ SUCCESS! API is now returning CORRECT values.")
                print("The fix has been successfully applied!")
            else:
                print("❌ Values still incorrect")
                if not debit_correct:
                    print(f"   - debit is {row.get('debit')}, expected 0")
                if not credit_correct:
                    print(f"   - credit is {row.get('credit')}, expected 7967855")
        else:
            print("❌ Cannot find 繰越利益剰余金合計 row")
            print("Last 5 rows:")
            for row in data[-5:]:
                if isinstance(row, dict):
                    print(f"  {row.get('account_name')}: debit={row.get('debit')}, credit={row.get('credit')}")
    
except Exception as e:
    print(f"❌ Error: {type(e).__name__}: {e}")
    import traceback
    traceback.print_exc()
    print("\nMake sure the backend is running on http://127.0.0.1:18080")
