"""介護保険デバッグスクリプト"""
import psycopg
from datetime import date
from decimal import Decimal

# 接続
conn = psycopg.connect('host=192.168.0.61 port=55432 dbname=njts_acct user=njts_app password=njts_app2025')
cur = conn.cursor()

# 従業員情報取得
cur.execute("SELECT employee_id, employee_code, name, birth_date FROM employees WHERE employee_code = '20190001'")
emp = cur.fetchone()
print(f'従業員: ID={emp[0]}, コード={emp[1]}, 名前={emp[2]}, 生年月日={emp[3]}')

# 年齢計算
birth_date = emp[3]
payment_date = date(2025, 12, 25)
age = payment_date.year - birth_date.year
if (payment_date.month, payment_date.day) < (birth_date.month, birth_date.day):
    age -= 1
print(f'\n支給日: {payment_date}')
print(f'年齢: {age}歳')
print(f'介護保険対象: {40 <= age < 65}')

# 2025年介護保険料率取得
print('\n=== 介護保険料率検索 ===')
cur.execute("""
    SELECT rate_id, rate_year, rate_type, calculation_target, employee_rate, employer_rate, prefecture 
    FROM insurance_rates 
    WHERE rate_type = '介護保険'
    AND rate_year = 2025
    AND calculation_target = '給与'
    ORDER BY rate_id DESC
    LIMIT 1
""")
rate = cur.fetchone()
if rate:
    print(f'料率ID: {rate[0]}')
    print(f'年度: {rate[1]}')
    print(f'種類: {rate[2]}')
    print(f'計算対象: {rate[3]}')
    print(f'従業員負担率: {rate[4]} ({float(rate[4])*100:.3f}%)')
    print(f'会社負担率: {rate[5]} ({float(rate[5])*100:.3f}%)')
    print(f'都道府県: {rate[6]}')
else:
    print('料率が見つかりません!')

# 給与設定取得
print('\n=== 給与設定 ===')
cur.execute("""
    SELECT base_salary FROM salary_settings 
    WHERE employee_id = %s 
    AND valid_from <= %s
    AND (valid_to IS NULL OR valid_to >= %s)
    ORDER BY valid_from DESC
    LIMIT 1
""", (emp[0], payment_date, payment_date))
salary = cur.fetchone()
if salary:
    print(f'基本給: ¥{salary[0]:,}')
else:
    print('給与設定が見つかりません!')

# 計算
if rate and salary:
    print('\n=== 介護保険計算 ===')
    base = Decimal(str(salary[0]))
    rate_val = Decimal(str(rate[4]))  # employee_rate
    care_ins = (base * rate_val).quantize(Decimal('1'))
    print(f'計算式: ¥{base:,} × {rate_val} = ¥{care_ins:,}')

# 実際の給与データ確認
print('\n=== 実際の給与データ ===')
cur.execute("""
    SELECT payroll_id, payment_date, base_salary, health_insurance, care_insurance, status
    FROM monthly_payroll 
    WHERE employee_id = %s 
    AND EXTRACT(YEAR FROM payment_date) = 2025
    AND EXTRACT(MONTH FROM payment_date) = 12
    ORDER BY payroll_id DESC
    LIMIT 1
""", (emp[0],))
payroll = cur.fetchone()
if payroll:
    print(f'給与ID: {payroll[0]}')
    print(f'支給日: {payroll[1]}')
    print(f'基本給: ¥{payroll[2]:,}')
    print(f'健康保険: ¥{payroll[3]:,}')
    print(f'介護保険: ¥{payroll[4]:,}')
    print(f'ステータス: {payroll[5]}')
else:
    print('2025年12月の給与データが見つかりません!')

conn.close()
