#!/usr/bin/env python3
"""
通过HTTP直接调用后端API，查看试算表
"""
import urllib.request
import json
from datetime import datetime

try:
    # 调用试算表API
    url = "http://localhost:18080/trial-balance?fiscal_year=2025&date_from=2025-06-01&date_to=2025-06-30"
    
    req = urllib.request.Request(url)
    with urllib.request.urlopen(req, timeout=10) as response:
        data = json.loads(response.read())
        
        print("=" * 100)
        print("【通过API获取的試算表（701科目）】")
        print("=" * 100)
        
        # 打印返回数据的类型和前几条
        print(f"\n返回数据类型: {type(data)}")
        print(f"数据长度: {len(data) if isinstance(data, (list, dict)) else 'N/A'}")
        
        if isinstance(data, list) and len(data) > 0:
            # 找701科目
            for account in data:
                if isinstance(account, dict) and account.get('account_code') == '701':
                    print(f"\n科目: {account['account_name']} (code: {account['account_code']})")
                    print(f"  借方: {account['debit']:,.0f}")
                    print(f"  貸方: {account['credit']:,.0f}")
                    break
            
            # 计算总数
            total_debit = sum(a['debit'] for a in data if isinstance(a, dict))
            total_credit = sum(a['credit'] for a in data if isinstance(a, dict))
            
            print(f"\n試算表合計：")
            print(f"  総借方: {total_debit:,.0f}")
            print(f"  総貸方: {total_credit:,.0f}")
            print(f"  平衡: {total_debit == total_credit}")
        else:
            print(f"\nAPI返回数据: {data}")
        
except Exception as e:
    print(f'錯誤: {e}')
    import traceback
    traceback.print_exc()
