"""Drop old CMS intermediary tables, recreate articles + published_scenarios.

article_templates and template_data are replaced by git-based .md.jinja
template files + direct DuckDB reads. Nothing was published yet so
this is a clean-slate migration.

published_scenarios and articles had FK references to template_data(id).
SQLite requires full table recreation to remove FK columns, so we do
the standard create-copy-drop-rename dance for both tables.
"""


def up(conn):
    # ── 1. Drop articles FTS triggers + virtual table ──────────────────
    conn.execute("DROP TRIGGER IF EXISTS articles_ai")
    conn.execute("DROP TRIGGER IF EXISTS articles_ad")
    conn.execute("DROP TRIGGER IF EXISTS articles_au")
    conn.execute("DROP TABLE IF EXISTS articles_fts")

    # ── 2. Drop old intermediary tables ────────────────────────────────
    conn.execute("DROP TABLE IF EXISTS template_data")
    conn.execute("DROP TABLE IF EXISTS article_templates")

    # ── 3. Recreate published_scenarios without template_data_id FK ────
    conn.execute("""
        CREATE TABLE published_scenarios_new (
            id           INTEGER PRIMARY KEY AUTOINCREMENT,
            slug         TEXT UNIQUE NOT NULL,
            title        TEXT NOT NULL,
            subtitle     TEXT,
            location     TEXT NOT NULL,
            country      TEXT NOT NULL,
            venue_type   TEXT NOT NULL DEFAULT 'indoor',
            ownership    TEXT NOT NULL DEFAULT 'rent',
            court_config TEXT NOT NULL,
            state_json   TEXT NOT NULL,
            calc_json    TEXT NOT NULL,
            created_at   TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at   TEXT
        )
    """)
    conn.execute("""
        INSERT INTO published_scenarios_new
            (id, slug, title, subtitle, location, country,
             venue_type, ownership, court_config, state_json, calc_json,
             created_at, updated_at)
        SELECT id, slug, title, subtitle, location, country,
               venue_type, ownership, court_config, state_json, calc_json,
               created_at, updated_at
        FROM published_scenarios
    """)
    conn.execute("DROP TABLE published_scenarios")
    conn.execute("ALTER TABLE published_scenarios_new RENAME TO published_scenarios")
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_pub_scenarios_slug"
        " ON published_scenarios(slug)"
    )

    # ── 4. Recreate articles without template_data_id, add SSG columns ─
    conn.execute("""
        CREATE TABLE articles_new (
            id               INTEGER PRIMARY KEY AUTOINCREMENT,
            url_path         TEXT UNIQUE NOT NULL,
            slug             TEXT UNIQUE NOT NULL,
            title            TEXT NOT NULL,
            meta_description TEXT,
            country          TEXT,
            region           TEXT,
            og_image_url     TEXT,
            status           TEXT NOT NULL DEFAULT 'draft',
            published_at     TEXT,
            template_slug    TEXT,
            language         TEXT NOT NULL DEFAULT 'en',
            date_modified    TEXT,
            seo_head         TEXT,
            created_at       TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at       TEXT
        )
    """)
    conn.execute("""
        INSERT INTO articles_new
            (id, url_path, slug, title, meta_description, country, region,
             og_image_url, status, published_at, created_at, updated_at)
        SELECT id, url_path, slug, title, meta_description, country, region,
               og_image_url, status, published_at, created_at, updated_at
        FROM articles
    """)
    conn.execute("DROP TABLE articles")
    conn.execute("ALTER TABLE articles_new RENAME TO articles")
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_articles_url_path ON articles(url_path)"
    )
    conn.execute("CREATE INDEX IF NOT EXISTS idx_articles_slug ON articles(slug)")
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_articles_status"
        " ON articles(status, published_at)"
    )

    # ── 5. Recreate articles FTS + triggers ────────────────────────────
    conn.execute("""
        CREATE VIRTUAL TABLE IF NOT EXISTS articles_fts USING fts5(
            title, meta_description, country, region,
            content='articles', content_rowid='id'
        )
    """)
    conn.execute("""
        CREATE TRIGGER IF NOT EXISTS articles_ai AFTER INSERT ON articles BEGIN
            INSERT INTO articles_fts(rowid, title, meta_description, country, region)
            VALUES (new.id, new.title, new.meta_description, new.country, new.region);
        END
    """)
    conn.execute("""
        CREATE TRIGGER IF NOT EXISTS articles_ad AFTER DELETE ON articles BEGIN
            INSERT INTO articles_fts(articles_fts, rowid, title, meta_description, country, region)
            VALUES ('delete', old.id, old.title, old.meta_description, old.country, old.region);
        END
    """)
    conn.execute("""
        CREATE TRIGGER IF NOT EXISTS articles_au AFTER UPDATE ON articles BEGIN
            INSERT INTO articles_fts(articles_fts, rowid, title, meta_description, country, region)
            VALUES ('delete', old.id, old.title, old.meta_description, old.country, old.region);
            INSERT INTO articles_fts(rowid, title, meta_description, country, region)
            VALUES (new.id, new.title, new.meta_description, new.country, new.region);
        END
    """)
