"""
更新系統狀態為 operational
"""
import psycopg2
from datetime import datetime

conn = psycopg2.connect(
    host="10.1.0.20",
    port=5433,
    database="hr_portal",
    user="admin",
    password="DC1qaz2wsx"
)
conn.autocommit = False
cur = conn.cursor()

try:
    print("Updating installation_system_status...")

    cur.execute("""
        UPDATE installation_system_status
        SET previous_phase = current_phase,
            current_phase = 'operational',
            phase_changed_at = NOW(),
            phase_changed_by = 'installer',
            phase_change_reason = '初始化完成，系統進入正式運作階段',
            initialization_completed = TRUE,
            initialized_at = NOW(),
            initialized_by = 'installer',
            operational_since = NOW()
        WHERE id = 1;
    """)

    conn.commit()
    print("SUCCESS: System status updated to 'operational'")

    # 驗證
    cur.execute("""
        SELECT current_phase, initialization_completed, operational_since
        FROM installation_system_status
        WHERE id = 1;
    """)
    result = cur.fetchone()
    if result:
        print(f"\nVerified:")
        print(f"  Current Phase: {result[0]}")
        print(f"  Initialization Completed: {result[1]}")
        print(f"  Operational Since: {result[2]}")

except Exception as e:
    conn.rollback()
    print(f"ERROR: {e}")
    import traceback
    traceback.print_exc()
finally:
    cur.close()
    conn.close()
