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

from app.core.database import get_connection

# SQLファイルを読み込んで実行
with open('sql/insert_opening_balances_2025.sql', 'r', encoding='utf-8') as f:
    sql_content = f.read()

# セミコロンで分割して実行
statements = [s.strip() for s in sql_content.split(';') if s.strip() and not s.strip().startswith('--')]

with get_connection() as conn:
    with conn.cursor() as cur:
        for statement in statements:
            if statement.strip():
                try:
                    cur.execute(statement)
                    print(f"✓ 実行成功")
                except Exception as e:
                    print(f"✗ エラー: {e}")
        
        conn.commit()
        print("\n前期残高データを更新しました。")
        
        # 確認
        cur.execute("""
            SELECT 
                a.account_code,
                a.account_name,
                ob.opening_debit,
                ob.opening_credit
            FROM opening_balances ob
            JOIN accounts a ON ob.account_id = a.account_id
            WHERE ob.fiscal_year = 2025
            ORDER BY a.account_code
        """)
        
        print("\n【2025年度 前期残高一覧】")
        for row in cur.fetchall():
            print(f"{row['account_code']} {row['account_name']:20s} 借方:{row['opening_debit']:>12,} 貸方:{row['opening_credit']:>12,}")
