# Generated by hand on 2025-12-31
# Upgrades crawls_crawl table from v0.8.6rc0 to v0.9.0

from django.db import migrations, connection


def upgrade_crawl_table_from_v086(apps, schema_editor):
    """Upgrade crawls_crawl table from v0.8.6rc0 schema to v0.9.0 schema."""
    cursor = connection.cursor()

    # Check if crawls_crawl table exists
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='crawls_crawl'")
    if not cursor.fetchone():
        return

    # Detect schema version
    cursor.execute("PRAGMA table_info(crawls_crawl)")
    crawl_cols = {row[1] for row in cursor.fetchall()}
    has_seed_id = 'seed_id' in crawl_cols
    has_urls = 'urls' in crawl_cols

    # Only upgrade if we have v0.8.6rc0 schema
    if not (has_seed_id and not has_urls):
        return

    # Check if table has any rows
    cursor.execute("SELECT COUNT(*) FROM crawls_crawl")
    has_data = cursor.fetchone()[0] > 0

    # v0.8.6rc0 schema - upgrade to v0.9.0
    if has_data:
        print('Upgrading crawls_crawl from v0.8.6rc0 to v0.9.0...')

    cursor.execute("""
        CREATE TABLE IF NOT EXISTS crawls_crawl_new (
            id TEXT PRIMARY KEY NOT NULL,
            created_at DATETIME NOT NULL,
            modified_at DATETIME NOT NULL,
            num_uses_succeeded INTEGER NOT NULL DEFAULT 0,
            num_uses_failed INTEGER NOT NULL DEFAULT 0,

            urls TEXT NOT NULL,
            config TEXT,
            max_depth INTEGER NOT NULL DEFAULT 0,
            tags_str VARCHAR(1024) NOT NULL DEFAULT '',
            persona_id TEXT,
            label VARCHAR(64) NOT NULL DEFAULT '',
            notes TEXT NOT NULL DEFAULT '',
            output_dir VARCHAR(512) NOT NULL DEFAULT '',

            status VARCHAR(15) NOT NULL DEFAULT 'queued',
            retry_at DATETIME,
            created_by_id INTEGER NOT NULL,
            schedule_id TEXT,

            FOREIGN KEY (created_by_id) REFERENCES auth_user(id) ON DELETE CASCADE,
            FOREIGN KEY (schedule_id) REFERENCES crawls_crawlschedule(id) ON DELETE SET NULL
        );
    """)

    if has_data:
        cursor.execute("""
            INSERT OR IGNORE INTO crawls_crawl_new (
                id, created_at, modified_at, num_uses_succeeded, num_uses_failed,
                urls, config, max_depth, tags_str, persona_id, label, notes, output_dir,
                status, retry_at, created_by_id, schedule_id
            )
            SELECT
                id, created_at, modified_at, num_uses_succeeded, num_uses_failed,
                '', config, max_depth, tags_str, NULL, '', '', '',
                status, retry_at, created_by_id, schedule_id
            FROM crawls_crawl;
        """)

    cursor.execute("DROP TABLE crawls_crawl;")
    cursor.execute("ALTER TABLE crawls_crawl_new RENAME TO crawls_crawl;")

    cursor.execute("CREATE INDEX IF NOT EXISTS crawls_crawl_status_idx ON crawls_crawl(status);")
    cursor.execute("CREATE INDEX IF NOT EXISTS crawls_crawl_retry_at_idx ON crawls_crawl(retry_at);")
    cursor.execute("CREATE INDEX IF NOT EXISTS crawls_crawl_created_at_idx ON crawls_crawl(created_at);")
    cursor.execute("CREATE INDEX IF NOT EXISTS crawls_crawl_created_by_id_idx ON crawls_crawl(created_by_id);")
    cursor.execute("CREATE INDEX IF NOT EXISTS crawls_crawl_schedule_id_idx ON crawls_crawl(schedule_id);")

    if has_data:
        print('✓ crawls_crawl upgraded to v0.9.0')


class Migration(migrations.Migration):

    dependencies = [
        ('crawls', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(
            upgrade_crawl_table_from_v086,
            reverse_code=migrations.RunPython.noop,
        ),
    ]
