"""
scrylo/db/migrate.py
---------------------
Additive schema migrations — safe to run repeatedly.
Adds columns that don't exist yet, never drops existing data.

Run automatically on startup via scrylo.db.session.init_db().
"""

from __future__ import annotations

import logging
import sqlite3

from scrylo.core.config import DB_PATH

log = logging.getLogger("scrylo.migrate")

# Each entry: (column_name, sql_type, default_value_sql)
_NEW_COLUMNS: list[tuple[str, str, str]] = [
    ("github_url",      "TEXT",    "NULL"),
    ("twitter_url",     "TEXT",    "NULL"),
    ("sources",         "TEXT",    "NULL"),   # JSON list: ["ddg","crunchbase","gh"]
    ("contact_method",  "TEXT",    "'email'"),# "email" | "linkedin_dm" | "both"
    ("phone",           "TEXT",    "NULL"),
    ("industry",        "TEXT",    "NULL"),
]


def run_migrations() -> None:
    """Add any missing columns to the leads table. Safe to call every startup."""
    db_path = str(DB_PATH)
    try:
        con = sqlite3.connect(db_path)
        cur = con.cursor()
        cur.execute("PRAGMA table_info(leads)")
        existing = {row[1] for row in cur.fetchall()}

        for col, typ, default in _NEW_COLUMNS:
            if col not in existing:
                sql = f"ALTER TABLE leads ADD COLUMN {col} {typ} DEFAULT {default}"
                cur.execute(sql)
                log.info("Migration: added column leads.%s", col)

        con.commit()
        con.close()
    except Exception as e:
        log.warning("Migration warning (non-fatal): %s", e)
