"""
Run this once to apply all pending migrations.
Usage:  python apply_migrations.py
"""
import sqlite3, datetime, os, sys

DB = os.path.join(os.path.dirname(__file__), 'db.sqlite3')
if not os.path.exists(DB):
    print(f"ERROR: database not found at {DB}")
    sys.exit(1)

conn = sqlite3.connect(DB)
cur  = conn.cursor()
now  = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')

def col_exists(table, col):
    cur.execute(f'PRAGMA table_info("{table}")')
    return any(r[1] == col for r in cur.fetchall())

def table_exists(name):
    cur.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,))
    return cur.fetchone() is not None

def migration_applied(app, name):
    cur.execute("SELECT 1 FROM django_migrations WHERE app=? AND name=?", (app, name))
    return cur.fetchone() is not None

def mark_applied(app, name):
    if not migration_applied(app, name):
        cur.execute("INSERT INTO django_migrations (app,name,applied) VALUES (?,?,?)", (app, name, now))
        print(f"  [recorded] {app} {name}")

# ── sales_projectassessment ───────────────────────────────────────────────
if not table_exists('sales_projectassessment'):
    cur.execute("""
    CREATE TABLE "sales_projectassessment" (
        "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
        "name" varchar(150) NOT NULL,
        "email" varchar(254) NOT NULL,
        "phone" varchar(30) NOT NULL DEFAULT '',
        "company" varchar(150) NOT NULL DEFAULT '',
        "service_type" varchar(30) NOT NULL DEFAULT 'web',
        "project_description" text NOT NULL DEFAULT '',
        "features_requested" text NOT NULL DEFAULT '',
        "budget" varchar(20) NOT NULL DEFAULT 'discuss',
        "timeline" varchar(20) NOT NULL DEFAULT 'flexible',
        "reference_sites" text NOT NULL DEFAULT '',
        "est_weeks_min" smallint unsigned NULL,
        "est_weeks_max" smallint unsigned NULL,
        "est_cost_min" decimal(10,2) NULL,
        "est_cost_max" decimal(10,2) NULL,
        "internal_notes" text NOT NULL DEFAULT '',
        "status" varchar(20) NOT NULL DEFAULT 'new',
        "ip_address" char(39) NULL,
        "created_at" datetime NOT NULL,
        "updated_at" datetime NOT NULL,
        "tenant_id" bigint NULL REFERENCES "tenants_tenant" ("id")
    )""")
    print("Created: sales_projectassessment")
mark_applied('sales', '0002_projectassessment')

# ── extra columns (migration 0003 + recent additions) ────────────────────
extra_cols = [
    ("title",                "varchar(10) NOT NULL DEFAULT ''"),
    ("first_name",           "varchar(75) NOT NULL DEFAULT ''"),
    ("last_name",            "varchar(75) NOT NULL DEFAULT ''"),
    ("position",             "varchar(100) NOT NULL DEFAULT ''"),
    ("heard_from",           "varchar(20) NOT NULL DEFAULT ''"),
    ("ai_label",             "varchar(200) NOT NULL DEFAULT ''"),
    ("ai_feasibility_score", "smallint NULL"),
    ("ai_market_note",       "text NOT NULL DEFAULT ''"),
    ("ai_verdict",           "varchar(30) NOT NULL DEFAULT ''"),
    ("ai_analysed_at",       "datetime NULL"),
]
for col, typedef in extra_cols:
    if not col_exists('sales_projectassessment', col):
        cur.execute(f'ALTER TABLE "sales_projectassessment" ADD COLUMN "{col}" {typedef}')
        print(f"  Added column: {col}")
mark_applied('sales', '0003_projectassessment_ai_fields')

# ── pages_sociallink ──────────────────────────────────────────────────────
if not table_exists('pages_sociallink'):
    cur.execute("""
    CREATE TABLE "pages_sociallink" (
        "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
        "platform" varchar(20) NOT NULL,
        "url" varchar(200) NOT NULL,
        "is_active" bool NOT NULL DEFAULT 1,
        "order" smallint unsigned NOT NULL DEFAULT 0,
        "tenant_id" bigint NULL REFERENCES "tenants_tenant" ("id")
    )""")
    print("Created: pages_sociallink")
mark_applied('pages', '0002_sociallink')

# ── ecommerce tables ──────────────────────────────────────────────────────
if not table_exists('ecommerce_product'):
    cur.execute("""
    CREATE TABLE "ecommerce_product" (
        "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
        "name" varchar(200) NOT NULL,
        "slug" varchar(200) NOT NULL UNIQUE,
        "product_type" varchar(20) NOT NULL DEFAULT 'service',
        "billing_cycle" varchar(20) NOT NULL DEFAULT 'one_time',
        "description" text NOT NULL DEFAULT '',
        "short_description" varchar(300) NOT NULL DEFAULT '',
        "price" decimal(10,2) NOT NULL DEFAULT 0,
        "deposit_amount" decimal(10,2) NULL,
        "stripe_price_id" varchar(100) NOT NULL DEFAULT '',
        "stripe_product_id" varchar(100) NOT NULL DEFAULT '',
        "domain_tld" varchar(20) NOT NULL DEFAULT '',
        "disk_space" varchar(50) NOT NULL DEFAULT '',
        "bandwidth" varchar(50) NOT NULL DEFAULT '',
        "is_active" bool NOT NULL DEFAULT 1,
        "is_featured" bool NOT NULL DEFAULT 0,
        "order" smallint unsigned NOT NULL DEFAULT 0,
        "created_at" datetime NOT NULL,
        "updated_at" datetime NOT NULL,
        "tenant_id" bigint NULL REFERENCES "tenants_tenant" ("id")
    )""")
    print("Created: ecommerce_product")

if not table_exists('ecommerce_order'):
    cur.execute("""
    CREATE TABLE "ecommerce_order" (
        "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
        "order_number" varchar(20) NOT NULL UNIQUE,
        "customer_name" varchar(150) NOT NULL,
        "customer_email" varchar(254) NOT NULL,
        "customer_phone" varchar(30) NOT NULL DEFAULT '',
        "total" decimal(10,2) NOT NULL DEFAULT 0,
        "amount_paid" decimal(10,2) NOT NULL DEFAULT 0,
        "status" varchar(20) NOT NULL DEFAULT 'pending',
        "is_deposit_order" bool NOT NULL DEFAULT 0,
        "stripe_payment_intent_id" varchar(200) NOT NULL DEFAULT '',
        "notes" text NOT NULL DEFAULT '',
        "paid_at" datetime NULL,
        "created_at" datetime NOT NULL,
        "updated_at" datetime NOT NULL,
        "tenant_id" bigint NULL REFERENCES "tenants_tenant" ("id")
    )""")
    print("Created: ecommerce_order")

if not table_exists('ecommerce_orderitem'):
    cur.execute("""
    CREATE TABLE "ecommerce_orderitem" (
        "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
        "product_name" varchar(200) NOT NULL,
        "product_type" varchar(20) NOT NULL DEFAULT 'service',
        "unit_price" decimal(10,2) NOT NULL DEFAULT 0,
        "quantity" integer NOT NULL DEFAULT 1,
        "domain_name" varchar(100) NOT NULL DEFAULT '',
        "order_id" bigint NOT NULL REFERENCES "ecommerce_order" ("id"),
        "product_id" bigint NULL REFERENCES "ecommerce_product" ("id")
    )""")
    print("Created: ecommerce_orderitem")

if not table_exists('ecommerce_domainregistration'):
    cur.execute("""
    CREATE TABLE "ecommerce_domainregistration" (
        "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
        "domain_name" varchar(100) NOT NULL,
        "status" varchar(20) NOT NULL DEFAULT 'pending',
        "registrar_order_id" varchar(100) NOT NULL DEFAULT '',
        "registered_at" datetime NULL,
        "expires_at" datetime NULL,
        "order_item_id" bigint NOT NULL UNIQUE REFERENCES "ecommerce_orderitem" ("id")
    )""")
    print("Created: ecommerce_domainregistration")
mark_applied('ecommerce', '0001_initial')

conn.commit()
conn.close()
print("\nDone. All migrations applied successfully.")
