"""
Database migration: Add pdf_path column to car_performance_checks table

Usage:
    cd backend
    python scripts/add_pdf_path_column.py
"""

import os
import sys

# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import create_engine, text
from sqlalchemy.exc import OperationalError

DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./autonetsellcar.db")


def add_pdf_path_column():
    """Add pdf_path column to car_performance_checks table"""

    engine = create_engine(DATABASE_URL)

    try:
        with engine.connect() as conn:
            # Check if column already exists
            if "sqlite" in DATABASE_URL:
                result = conn.execute(text("PRAGMA table_info(car_performance_checks)"))
                columns = [row[1] for row in result.fetchall()]
                if "pdf_path" in columns:
                    print("Column 'pdf_path' already exists. Nothing to do.")
                    return
            else:
                # PostgreSQL
                result = conn.execute(text("""
                    SELECT column_name
                    FROM information_schema.columns
                    WHERE table_name = 'car_performance_checks'
                    AND column_name = 'pdf_path'
                """))
                if result.fetchone():
                    print("Column 'pdf_path' already exists. Nothing to do.")
                    return

            # Add the column
            print("Adding 'pdf_path' column to car_performance_checks table...")
            conn.execute(text(
                "ALTER TABLE car_performance_checks ADD COLUMN pdf_path VARCHAR(500)"
            ))
            conn.commit()
            print("Column 'pdf_path' added successfully!")

    except OperationalError as e:
        if "duplicate column" in str(e).lower() or "already exists" in str(e).lower():
            print("Column 'pdf_path' already exists. Nothing to do.")
        else:
            raise


if __name__ == "__main__":
    add_pdf_path_column()
