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

# PostgreSQL接続情報を設定
os.environ['DB_HOST'] = 'localhost'
os.environ['DB_NAME'] = 'accounting_db'
os.environ['DB_USER'] = 'postgres'
os.environ['DB_PASSWORD'] = 'root'
os.environ['DB_PORT'] = '5432'

# backendパスを追加
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))

from app.core.database import get_connection

print("データベース接続テスト...")

with get_connection() as conn:
    with conn.cursor() as cur:
        # 最初のテスト: 701の全ての6月データ
        print("\n=== テスト1: 701の全ての6月クレジットデータ ===")
        sql = """
        SELECT 
            COALESCE(SUM(l.credit), 0) as total_credit
        FROM journal_lines l
        JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
        WHERE l.account_id = 701
          AND EXTRACT(YEAR FROM e.entry_date) = 2025
          AND EXTRACT(MONTH FROM e.entry_date) = 6
        """
        
        cur.execute(sql)
        result = cur.fetchone()
        print(f"素のSUMクエリ結果: {result['total_credit']}")
        
        # テスト2: ユーザーが期待する値
        print("\n=== テスト2: ユーザー期待値との比較 ===")
        print(f"実際の値: {result['total_credit']}")
        print(f"期待値: 4082728")
        print(f"差異: {result['total_credit'] - 4082728}")
        
        # テスト3: 詳細なデータ確認
        print("\n=== テスト3: 6月の全トランザクション詳細 ===")
        sql_detail = """
        SELECT 
            e.journal_entry_id,
            e.entry_date,
            e.description,
            l.credit,
            e.is_deleted,
            e.parent_entry_id
        FROM journal_lines l
        JOIN journal_entries e ON e.journal_entry_id = l.journal_entry_id
        WHERE l.account_id = 701
          AND EXTRACT(YEAR FROM e.entry_date) = 2025
          AND EXTRACT(MONTH FROM e.entry_date) = 6
        ORDER BY e.entry_date, e.journal_entry_id
        """
        
        cur.execute(sql_detail)
        rows = cur.fetchall()
        
        total = 0
        for row in rows:
            status = []
            if row['is_deleted']:
                status.append("DELETED")
            if row['parent_entry_id']:
                status.append(f"correction(parent={row['parent_entry_id']})")
            status_str = " | ".join(status) if status else "OK"
            
            print(f"ID:{row['journal_entry_id']:5d} | {row['entry_date']} | {row['description']:35s} | " +
                  f"credit:{row['credit']:>12,.0f} | {status_str}")
            total += row['credit']
        
        print(f"\n合計: {total:,.0f}")

print("\n処理完了")
