#!/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()

try:
    response = requests.get(url, params=params)
    response.raise_for_status()
    data = response.json()
    
    if isinstance(data, dict) and 'accounts' in data:
        accounts = data['accounts']
        
        # Find the target row
        target = [row for row in accounts if row.get('account_name') == '繰越利益剰余金合計']
        
        if target:
            row = target[0]
            print("✓ 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()
            
            # Convert to float for comparison (handles both "0" and "0.00")
            try:
                debit_correct = float(row.get('debit', '0')) == 0.0
                credit_correct = float(row.get('credit', '0')) == 7967855.0
            except (ValueError, TypeError):
                debit_correct = False
                credit_correct = False
            
            if debit_correct and credit_correct:
                print("✅✅✅ SUCCESS!")
                print("✅ API is now returning CORRECT values!")
                print("✅ The fix has been successfully applied and verified!")
            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("\nLast 5 rows:")
            for row in accounts[-5:]:
                print(f"  {row.get('account_name')}: debit={row.get('debit')}, credit={row.get('credit')}")
    else:
        print("Unexpected response structure")
        print(json.dumps(data, indent=2, ensure_ascii=False)[:200])
    
except Exception as e:
    print(f"❌ Error: {type(e).__name__}: {e}")
    import traceback
    traceback.print_exc()
