import psycopg2
from psycopg2 import sql

# 嘗試用 postgres 超級用户
try:
    conn = psycopg2.connect('host=192.168.0.61 port=55432 dbname=postgres user=postgres password=postgres')
except:
    # 如果失敗，嘗試現有用户
    conn = psycopg2.connect('host=192.168.0.61 port=55432 dbname=njts_acct user=njts_app password=njts_app2025')

cur = conn.cursor()
conn.set_isolation_level(0)  # autocommit mode

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

try:
    # 1. 檢查並添加欄位
    print("\n【步驟 1】添加新欄位...")
    
    # 逐個添加，處理可能已存在的情況
    try:
        cur.execute("ALTER TABLE journal_entries ADD COLUMN is_latest BOOLEAN DEFAULT true")
        print("✓ 欄位 is_latest 已添加")
    except psycopg2.errors.DuplicateColumn:
        print("✓ 欄位 is_latest 已存在")
    
    try:
        cur.execute("ALTER TABLE journal_entries ADD COLUMN revision_count INTEGER DEFAULT 1")
        print("✓ 欄位 revision_count 已添加")
    except psycopg2.errors.DuplicateColumn:
        print("✓ 欄位 revision_count 已存在")
    
    try:
        cur.execute("ALTER TABLE journal_entries ADD COLUMN original_entry_id INTEGER")
        print("✓ 欄位 original_entry_id 已添加")
    except psycopg2.errors.DuplicateColumn:
        print("✓ 欄位 original_entry_id 已存在")
    
    # 2. 創建索引
    print("\n【步驟 2】創建索引...")
    try:
        cur.execute("CREATE INDEX idx_journal_entries_is_latest ON journal_entries(is_latest, entry_date)")
        print("✓ 索引 idx_journal_entries_is_latest 已創建")
    except psycopg2.errors.DuplicateTable:
        print("✓ 索引已存在")
    
    try:
        cur.execute("CREATE INDEX idx_journal_entries_original_entry_id ON journal_entries(original_entry_id)")
        print("✓ 索引 idx_journal_entries_original_entry_id 已創建")
    except psycopg2.errors.DuplicateTable:
        print("✓ 索引已存在")
    
    # 3. 驗證
    print("\n【步驟 3】驗證新欄位...")
    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)

except Exception as e:
    print(f"\n❌ 錯誤: {e}")
    print("\n嘗試替代方案...")
    
    # 直接連接並嘗試
    conn2 = psycopg2.connect('host=192.168.0.61 port=55432 dbname=njts_acct user=njts_app password=njts_app2025')
    cur2 = conn2.cursor()
    
    # 查看表結構
    cur2.execute("""
    SELECT column_name 
    FROM information_schema.columns 
    WHERE table_name = 'journal_entries'
    ORDER BY ordinal_position
    """)
    
    print("\n【當前 journal_entries 表結構】")
    for row in cur2.fetchall():
        print(f"  - {row[0]}")
    
    conn2.close()

conn.close()
