"""
Migration: Add deleted_at column to projects table

Adds columns:
- projects.deleted_at: Timestamp set when status='deleted'; data hard-deleted after 60 days
"""

import sqlite3
import sys
from pathlib import Path


def migrate(db_path: str):
    """Run the migration."""
    print(f"Migrating database: {db_path}")

    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    try:
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='projects'")
        if not cursor.fetchone():
            print("projects table does not exist. Skipping migration.")
            return

        cursor.execute("PRAGMA table_info(projects)")
        existing_cols = {row[1] for row in cursor.fetchall()}

        if 'deleted_at' not in existing_cols:
            print("Adding deleted_at column to projects...")
            cursor.execute("ALTER TABLE projects ADD COLUMN deleted_at DATETIME")
        else:
            print("deleted_at column already exists. Skipping.")

        conn.commit()
        print("Migration completed successfully!")

    except Exception as e:
        print(f"Migration failed: {e}")
        conn.rollback()
        raise
    finally:
        conn.close()


if __name__ == "__main__":
    db_path = "./data/seismo_fleet.db"

    if len(sys.argv) > 1:
        db_path = sys.argv[1]

    if not Path(db_path).exists():
        print(f"Database not found: {db_path}")
        sys.exit(1)

    migrate(db_path)
