#!/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【 确认journal_lines表的字段用途 】\n')
        
        print('1. journal_lines 中的 account_id 存的是什么？')
        cur.execute("""
            SELECT DISTINCT l.account_id FROM journal_lines l LIMIT 5
        """)
        sample_ids = [row['account_id'] for row in cur.fetchall()]
        print(f"   样本account_id值: {sample_ids}")
        
        for aid in sample_ids[:2]:
            cur.execute("SELECT account_code, account_name FROM accounts WHERE account_id = %s", (aid,))
            row = cur.fetchone()
            if row:
                print(f"   - account_id={aid} 对应 account_code={row['account_code']}, name={row['account_name']}")
        
        print('\n2. 检查是否有任何地方用account_code作为外键：')
        # 检查外键约束
        cur.execute("""
            SELECT table_name, column_name, constraint_name
            FROM information_schema.key_column_usage  
            WHERE table_name = 'journal_lines'
            ORDER BY table_name
        """)
        print("   journal_lines表的外键:")
        has_fk = False
        for row in cur.fetchall():
            print(f"     - {row['column_name']}: {row['constraint_name']}")
            has_fk = True
        if not has_fk:
            print("     (没有外键约束)")
        
        print('\n3. journal_lines 中是否有account_code这个字段？')
        cur.execute("""
            SELECT column_name FROM information_schema.columns
            WHERE table_name = 'journal_lines'
            ORDER BY ordinal_position
        """)
        columns = [row['column_name'] for row in cur.fetchall()]
        print(f"   journal_lines的字段: {columns}")
        
        if 'account_code' in columns:
            print("   ⚠️ 有account_code字段！")
        else:
            print("   ✓ 没有account_code字段，只用account_id")
        
        print('\n4. 是否所有journal_lines的account_id都能在accounts表找到？')
        cur.execute("""
            SELECT COUNT(DISTINCT l.account_id) as total,
                   COUNT(DISTINCT CASE WHEN a.account_id IS NOT NULL THEN l.account_id END) as matched
            FROM journal_lines l
            LEFT JOIN accounts a ON a.account_id = l.account_id
        """)
        row = cur.fetchone()
        print(f"   总的不同account_id: {row['total']}")
        print(f"   能在accounts表匹配到的: {row['matched']}")
        
        if row['total'] != row['matched']:
            print("   ⚠️ 有孤立的account_id！")
            cur.execute("""
                SELECT DISTINCT l.account_id FROM journal_lines l
                LEFT JOIN accounts a ON a.account_id = l.account_id
                WHERE a.account_id IS NULL
            """)
            orphans = [r['account_id'] for r in cur.fetchall()]
            print(f"   孤立的account_id: {orphans}")
        else:
            print("   ✓ 全部都能匹配")
