#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
sys.path.insert(0, 'backend')

os.environ['DB_HOST'] = '192.168.0.61'
os.environ['DB_NAME'] = 'njts_acct'
os.environ['DB_USER'] = 'njts_app'
os.environ['DB_PASSWORD'] = 'njts_app2025'
os.environ['DB_PORT'] = '55432'

from app.core.database import get_connection

with get_connection() as conn:
    with conn.cursor() as cur:
        print('\n【 accounts 表 - 前20条 】')
        cur.execute("SELECT account_id, account_code, account_name FROM accounts ORDER BY account_code LIMIT 20")
        for row in cur.fetchall():
            print(f"account_id={row['account_id']:<3} account_code={row['account_code']:<5} account_name={row['account_name']}")

        print('\n【 查找 account_code=701 对应的 account_id 】')
        cur.execute("SELECT account_id, account_code, account_name FROM accounts WHERE account_code = '701'")
        row = cur.fetchone()
        if row:
            print(f"account_code='701' 对应的 account_id = {row['account_id']}")
            print(f"完整信息: {row}")
        else:
            print("未找到 account_code='701'")

        print('\n【 journal_lines 中 account_id 的唯一值 (前20个) 】')
        cur.execute("SELECT DISTINCT account_id FROM journal_lines ORDER BY account_id LIMIT 20")
        account_ids = [row['account_id'] for row in cur.fetchall()]
        print(f"journal_lines中的account_id: {account_ids}")

        print('\n【 2025年6月份的交易 - 查找 account_code=701 的交易 】')
        cur.execute("""
            SELECT 
              jl.journal_line_id,
              jl.journal_entry_id,
              jl.account_id,
              ac.account_code,
              ac.account_name,
              jl.debit,
              jl.credit
            FROM journal_lines jl
            JOIN accounts ac ON ac.account_id = jl.account_id
            JOIN journal_entries je ON je.journal_entry_id = jl.journal_entry_id
            WHERE ac.account_code = '701'
              AND je.entry_date >= '2025-06-01'
              AND je.entry_date <= '2025-06-30'
            ORDER BY jl.journal_line_id
            LIMIT 10
        """)
        cols = [desc[0] for desc in cur.description]
        print(f"找到的交易数: {cur.rowcount if hasattr(cur, 'rowcount') else '未知'}")
        for row in cur.fetchall():
            print(f"  {row['journal_entry_id']:>5} | {row['account_id']:>3} | {row['account_code']:>5} | {row['debit']:>10} | {row['credit']:>10}")
