#!/usr/bin/env python3
"""One-shot migration: add thumbnail_path column + partial index."""
import os
import sys
from pathlib import Path

import psycopg2
from dotenv import load_dotenv

load_dotenv(Path(__file__).parent / ".env")

conn = psycopg2.connect(
    host=os.getenv("DB_HOST"),
    port=int(os.getenv("DB_PORT", 5432)),
    dbname=os.getenv("DB_NAME"),
    user=os.getenv("DB_USER"),
    password=os.getenv("DB_PASSWORD"),
    connect_timeout=10,
)
conn.autocommit = True
cur = conn.cursor()

print("Step 1: ALTER TABLE ...", flush=True)
cur.execute("ALTER TABLE photos ADD COLUMN IF NOT EXISTS thumbnail_path VARCHAR(2000)")
print("  Done.", flush=True)

print("Step 2: CREATE INDEX CONCURRENTLY ...", flush=True)
cur.execute(
    "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_photos_thumbnail_path_null "
    "ON photos (id) WHERE thumbnail_path IS NULL"
)
print("  Done.", flush=True)

cur.execute(
    "SELECT column_name FROM information_schema.columns "
    "WHERE table_name='photos' AND column_name='thumbnail_path'"
)
row = cur.fetchone()
print(f"Verified column exists: {row is not None}", flush=True)

cur.close()
conn.close()
print("Migration complete.", flush=True)
