import psycopg2

conn = psycopg2.connect('host=192.168.0.61 port=55432 dbname=njts_acct user=njts_app password=njts_app2025')
cur = conn.cursor()

print("=" * 80)
print("【數據庫遷移：添加修正追踪欄位】")
print("=" * 80)

# 1. 添加新欄位
print("\n【步驟 1】添加新欄位...")
cur.execute("""
ALTER TABLE journal_entries 
ADD COLUMN IF NOT EXISTS is_latest BOOLEAN DEFAULT true,
ADD COLUMN IF NOT EXISTS revision_count INTEGER DEFAULT 1,
ADD COLUMN IF NOT EXISTS original_entry_id INTEGER REFERENCES journal_entries(journal_entry_id) ON DELETE CASCADE
""")
print("✓ 新欄位已添加")

# 2. 更新現有數據
print("\n【步驟 2】更新現有數據...")
cur.execute("""
UPDATE journal_entries 
SET is_latest = false 
WHERE is_deleted = true AND is_latest IS NOT NULL
""")
deleted_count = cur.rowcount
print(f"✓ 標記 {deleted_count} 條已刪除的交易為 is_latest=false")

cur.execute("""
UPDATE journal_entries 
SET is_latest = true 
WHERE is_deleted = false AND is_latest IS NULL
""")
active_count = cur.rowcount
print(f"✓ 標記 {active_count} 條活躍的交易為 is_latest=true")

# 3. 創建索引
print("\n【步驟 3】創建索引...")
cur.execute("""
CREATE INDEX IF NOT EXISTS idx_journal_entries_is_latest 
ON journal_entries(is_latest, entry_date)
""")
print("✓ 索引 idx_journal_entries_is_latest 已創建")

cur.execute("""
CREATE INDEX IF NOT EXISTS idx_journal_entries_original_entry_id 
ON journal_entries(original_entry_id)
""")
print("✓ 索引 idx_journal_entries_original_entry_id 已創建")

conn.commit()

# 驗證
print("\n【步驟 4】驗證新欄位...")
cur.execute("""
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'journal_entries' 
  AND column_name IN ('is_latest', 'revision_count', 'original_entry_id')
ORDER BY ordinal_position
""")

rows = cur.fetchall()
for col_name, data_type in rows:
    print(f"  ✓ {col_name}: {data_type}")

print("\n" + "=" * 80)
print("✓ 數據庫遷移完成！")
print("=" * 80)

conn.close()
