"""
Migration script to add project_number field to projects table.

This adds a new column for TMI internal project numbering:
- Format: xxxx-YY (e.g., "2567-23")
- xxxx = incremental project number
- YY = year project was started

Combined with client_name and name (project/site name), this enables
smart searching across all project identifiers.

Run this script once to migrate an existing database.
"""

import sqlite3
import os

# Database path
DB_PATH = "./data/seismo_fleet.db"


def migrate_database():
    """Add project_number column to projects table"""

    if not os.path.exists(DB_PATH):
        print(f"Database not found at {DB_PATH}")
        print("The database will be created automatically when you run the application.")
        return

    print(f"Migrating database: {DB_PATH}")

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

    # Check if projects table exists
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='projects'")
    table_exists = cursor.fetchone()

    if not table_exists:
        print("Projects table does not exist yet - will be created when app runs")
        conn.close()
        return

    # Check if project_number column already exists
    cursor.execute("PRAGMA table_info(projects)")
    columns = [col[1] for col in cursor.fetchall()]

    if 'project_number' in columns:
        print("Migration already applied - project_number column exists")
        conn.close()
        return

    print("Adding project_number column to projects table...")

    try:
        cursor.execute("ALTER TABLE projects ADD COLUMN project_number TEXT")
        print("  Added project_number column")

        # Create index for faster searching
        cursor.execute("CREATE INDEX IF NOT EXISTS ix_projects_project_number ON projects(project_number)")
        print("  Created index on project_number")

        # Also add index on client_name if it doesn't exist
        cursor.execute("CREATE INDEX IF NOT EXISTS ix_projects_client_name ON projects(client_name)")
        print("  Created index on client_name")

        conn.commit()
        print("\nMigration completed successfully!")

    except sqlite3.Error as e:
        print(f"\nError during migration: {e}")
        conn.rollback()
        raise

    finally:
        conn.close()


if __name__ == "__main__":
    migrate_database()
