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)

# 查找疑似重复的记录：相同描述和金额，但日期不同
cur.execute("""
    SELECT 
        je.description,
        COALESCE(SUM(jl.debit), 0) as debit_total,
        COALESCE(SUM(jl.credit), 0) as credit_total,
        COUNT(*) as cnt,
        STRING_AGG(
            je.journal_entry_id || '(' || TO_CHAR(je.entry_date, 'YYYY-MM-DD') || ')',
            ' | ' 
            ORDER BY je.entry_date
        ) as entries
    FROM journal_entries je
    LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
    WHERE je.is_deleted = false
      AND EXTRACT(YEAR FROM je.entry_date) = 2025
      AND EXTRACT(MONTH FROM je.entry_date) IN (6, 7, 8)
    GROUP BY je.description
    HAVING COUNT(*) > 1
    ORDER BY cnt DESC
""")

results = cur.fetchall()

if results:
    print("\n疑似重复记录（相同描述，多个月份）:\n")
    for row in results:
        description, debit, credit, cnt, entries = row
        print(f"【{cnt}件】{description}")
        print(f"  金額: 借={debit:>10,.0f}  貸={credit:>10,.0f}")
        print(f"  仕訳: {entries}")
        print()
else:
    print("未找到疑似重复的记录")

# 查询6月的所有记录
print("\n" + "=" * 120)
print("【6月の全仕訳】")
print("=" * 120)

cur.execute("""
    SELECT 
        je.journal_entry_id,
        je.entry_date,
        je.description,
        COALESCE(SUM(jl.debit), 0) as debit_total,
        COALESCE(SUM(jl.credit), 0) as credit_total
    FROM journal_entries je
    LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
    WHERE je.is_deleted = false
      AND EXTRACT(YEAR FROM je.entry_date) = 2025
      AND EXTRACT(MONTH FROM je.entry_date) = 6
    GROUP BY je.journal_entry_id, je.entry_date, je.description
    ORDER BY je.journal_entry_id
""")

june_records = cur.fetchall()
print(f"\n全{len(june_records)}件:")
for row in june_records:
    entry_id, entry_date, description, debit, credit = row
    print(f"ID={entry_id:3d} | {entry_date} | 借={debit:>10,.0f}  貸={credit:>10,.0f} | {description[:50]}")

# 查询只在7月、8月出现但6月没有的相同记录
print("\n" + "=" * 120)
print("【可能通过复制创建的记录（6月有，7月/8月也有相同金额）】")
print("=" * 120)

cur.execute("""
    WITH june_records AS (
        SELECT 
            je.description,
            COALESCE(SUM(jl.debit), 0) as debit_total,
            COALESCE(SUM(jl.credit), 0) as credit_total
        FROM journal_entries je
        LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
        WHERE je.is_deleted = false
          AND EXTRACT(YEAR FROM je.entry_date) = 2025
          AND EXTRACT(MONTH FROM je.entry_date) = 6
        GROUP BY je.description
    )
    SELECT 
        je.journal_entry_id,
        TO_CHAR(je.entry_date, 'YYYY-MM') as month,
        je.description,
        COALESCE(SUM(jl.debit), 0) as debit_total,
        COALESCE(SUM(jl.credit), 0) as credit_total
    FROM journal_entries je
    LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
    INNER JOIN june_records jr ON je.description = jr.description 
        AND COALESCE(SUM(jl.debit), 0) = jr.debit_total
        AND COALESCE(SUM(jl.credit), 0) = jr.credit_total
    WHERE je.is_deleted = false
      AND EXTRACT(YEAR FROM je.entry_date) = 2025
      AND EXTRACT(MONTH FROM je.entry_date) IN (7, 8)
    GROUP BY je.journal_entry_id, je.entry_date, je.description
    ORDER BY je.entry_date, je.journal_entry_id
""")

duplicates = cur.fetchall()

if duplicates:
    print(f"\n找到{len(duplicates)}件可能通过复制创建的记录:\n")
    for row in duplicates:
        entry_id, month, description, debit, credit = row
        print(f"ID={entry_id:3d} | {month} | 借={debit:>10,.0f}  貸={credit:>10,.0f} | {description[:50]}")
else:
    print("\n未找到可能通过复制创建的记录")

cur.close()
conn.close()
