"""Migration: create password_reset_tokens table.

Part of Phase 1 production hardening (password reset flow).

Usage:
    cd /home/vincent/projects/command-sovereignty
    .venv/bin/python scripts/migrate_password_reset.py
"""
import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from app.models import db

app = create_app()

with app.app_context():
    inspector = db.inspect(db.engine)
    tables = inspector.get_table_names()

    if 'password_reset_tokens' in tables:
        print("  ✓ password_reset_tokens table already exists")
    else:
        print("Creating password_reset_tokens table...")
        with db.engine.connect() as conn:
            conn.execute(db.text("""
                CREATE TABLE password_reset_tokens (
                    id VARCHAR(36) PRIMARY KEY,
                    user_id VARCHAR(36) NOT NULL
                        REFERENCES profiles(id) ON DELETE CASCADE,
                    token_hash VARCHAR(64) NOT NULL UNIQUE,
                    created_at DATETIME,
                    expires_at DATETIME NOT NULL,
                    used_at DATETIME
                )
            """))
            conn.execute(db.text(
                "CREATE INDEX IF NOT EXISTS ix_password_reset_tokens_user_id "
                "ON password_reset_tokens(user_id)"
            ))
            conn.execute(db.text(
                "CREATE INDEX IF NOT EXISTS ix_password_reset_tokens_token_hash "
                "ON password_reset_tokens(token_hash)"
            ))
            conn.commit()
        print("  ✓ Created")

    print("\nMigration complete!")
