import os
import psycopg2
from dotenv import load_dotenv

# Load environment variables
root_env = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')
load_dotenv(root_env)

# Connect to database
conn = psycopg2.connect(
    host=os.getenv('DB_HOST', '192.168.0.61'),
    port=os.getenv('DB_PORT', '55432'),
    dbname=os.getenv('DB_NAME', 'njts_acct'),
    user=os.getenv('DB_USER', 'njts_app'),
    password=os.getenv('DB_PASSWORD')
)

cur = conn.cursor()

print("保険率カラムを DECIMAL(7,5) に変更中...")
print("これにより、4.955% (0.04955) のような値を正確に保存できます。")

# Alter insurance_rates table to DECIMAL(7,5)
cur.execute("""
    ALTER TABLE insurance_rates 
    ALTER COLUMN employee_rate TYPE DECIMAL(7, 5),
    ALTER COLUMN employer_rate TYPE DECIMAL(7, 5)
""")

# Alter child_support_contribution_rates table
cur.execute("""
    ALTER TABLE child_support_contribution_rates 
    ALTER COLUMN contribution_rate TYPE DECIMAL(7, 5)
""")

conn.commit()

print("OK カラム変更完了")

# Verify
cur.execute("""
    SELECT column_name, numeric_precision, numeric_scale 
    FROM information_schema.columns 
    WHERE table_name='insurance_rates' 
    AND column_name IN ('employee_rate', 'employer_rate') 
    ORDER BY column_name
""")

print("\n変更後の insurance_rates カラム:")
for row in cur.fetchall():
    print(f"  {row[0]}: numeric({row[1]},{row[2]})")

cur.execute("""
    SELECT column_name, numeric_precision, numeric_scale 
    FROM information_schema.columns 
    WHERE table_name='child_support_contribution_rates' 
    AND column_name = 'contribution_rate'
""")

print("\n変更後の child_support_contribution_rates カラム:")
for row in cur.fetchall():
    print(f"  {row[0]}: numeric({row[1]},{row[2]})")

cur.close()
conn.close()

print("\n完了！")
print("これで 4.955% を入力すると、0.04955 として正確に保存され、4.955% と表示されます。")
