import psycopg2

conn = psycopg2.connect(
    host="192.168.0.61",
    port=55432,
    database="njts_acct",
    user="njts_app",
    password="njts_app2025"
)

cur = conn.cursor()

print("=" * 120)
print("【遠達ビル 事務所費用】详细分析")
print("=" * 120)

# 查询ID 444和445的journal_lines
for entry_id in [444, 445]:
    print(f"\n--- 仕訳入力ID={entry_id} ---")
    
    cur.execute("""
        SELECT 
            je.journal_entry_id,
            je.entry_date,
            je.description,
            je.is_latest,
            COUNT(*) as line_count
        FROM journal_entries je
        WHERE je.journal_entry_id = %s
        GROUP BY je.journal_entry_id, je.entry_date, je.description, je.is_latest
    """, (entry_id,))
    
    je_info = cur.fetchone()
    if je_info:
        entry_id, entry_date, description, is_latest, line_count = je_info
        print(f"日付: {entry_date}")
        print(f"説明: {description}")
        print(f"最新: {is_latest}")
        print(f"明細行数: {line_count}")
        
        # 取得该仕訳的所有明细行
        cur.execute("""
            SELECT 
                jl.journal_line_id,
                jl.account_id,
                a.account_code,
                a.account_name,
                jl.debit,
                jl.credit
            FROM journal_lines jl
            LEFT JOIN accounts a ON jl.account_id = a.account_id
            WHERE jl.journal_entry_id = %s
            ORDER BY jl.journal_line_id
        """, (entry_id,))
        
        lines = cur.fetchall()
        print(f"\n明細（全{len(lines)}行）:")
        for line_id, acc_id, code, name, debit, credit in lines:
            print(f"  Line {line_id}: [{code}] {name} | 借={debit or 0:>10,.0f}  貸={credit or 0:>10,.0f}")

# 现在检查是否有重复的journal_lines
print("\n" + "=" * 120)
print("【重複検出】journal_linesの重复行")
print("=" * 120)

cur.execute("""
    SELECT 
        journal_entry_id,
        account_id,
        debit,
        credit,
        COUNT(*) as cnt
    FROM journal_lines
    WHERE journal_entry_id IN (444, 445)
    GROUP BY journal_entry_id, account_id, debit, credit
    HAVING COUNT(*) > 1
""")

duplicates = cur.fetchall()
if duplicates:
    print("\n重复検出:")
    for entry_id, acc_id, debit, credit, cnt in duplicates:
        print(f"  ID={entry_id}, 科目={acc_id}, 借={debit}, 貸={credit} → {cnt}行重複")
else:
    print("\n重复行なし")

cur.close()
conn.close()
