"""Migration script to add subscription fields to users table."""
import sqlite3
import os
from pathlib import Path

# Get database path
db_path = Path(__file__).parent.parent / "audit_evidence.db"
if not db_path.exists():
    print(f"Database not found at {db_path}")
    exit(1)

print(f"Connecting to database: {db_path}")
conn = sqlite3.connect(str(db_path))
cursor = conn.cursor()

# Check if columns already exist
cursor.execute("PRAGMA table_info(users)")
columns = [col[1] for col in cursor.fetchall()]

# Add subscription_plan column if it doesn't exist
if 'subscription_plan' not in columns:
    print("Adding subscription_plan column...")
    cursor.execute("ALTER TABLE users ADD COLUMN subscription_plan VARCHAR")
else:
    print("subscription_plan column already exists")

# Add subscription_status column if it doesn't exist
if 'subscription_status' not in columns:
    print("Adding subscription_status column...")
    cursor.execute("ALTER TABLE users ADD COLUMN subscription_status VARCHAR DEFAULT 'inactive'")
else:
    print("subscription_status column already exists")

# Add stripe_customer_id column if it doesn't exist
if 'stripe_customer_id' not in columns:
    print("Adding stripe_customer_id column...")
    cursor.execute("ALTER TABLE users ADD COLUMN stripe_customer_id VARCHAR")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_users_stripe_customer_id ON users(stripe_customer_id)")
else:
    print("stripe_customer_id column already exists")

# Add stripe_subscription_id column if it doesn't exist
if 'stripe_subscription_id' not in columns:
    print("Adding stripe_subscription_id column...")
    cursor.execute("ALTER TABLE users ADD COLUMN stripe_subscription_id VARCHAR")
else:
    print("stripe_subscription_id column already exists")

# Add current_period_end column if it doesn't exist
if 'current_period_end' not in columns:
    print("Adding current_period_end column...")
    cursor.execute("ALTER TABLE users ADD COLUMN current_period_end DATETIME")
else:
    print("current_period_end column already exists")

conn.commit()
conn.close()

print("Migration completed successfully!")

