"""Idempotent init script para data/deals.db.

Crea schema + indexes. Safe para correr multiples veces (CREATE TABLE IF NOT EXISTS).

Usage:
    python scripts/init_deals_db.py
"""
from __future__ import annotations
import io, sys
from pathlib import Path

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from deals_db import init_db, _DB_PATH, _get_conn  # noqa: E402


def main() -> int:
    print(f"Initializing deals DB at: {_DB_PATH}")
    init_db()
    conn = _get_conn()

    # Verify all tables created
    tables = [r[0] for r in conn.execute(
        "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
    ).fetchall()]
    print(f"Tables present: {tables}")

    # Verify indexes
    indexes = [r[0] for r in conn.execute(
        "SELECT name FROM sqlite_master WHERE type='index' AND name NOT LIKE 'sqlite_%' ORDER BY name"
    ).fetchall()]
    print(f"Indexes present: {indexes}")

    # Sanity check
    expected_tables = {"deals", "scraper_runs", "firecrawl_usage"}
    missing = expected_tables - set(tables)
    if missing:
        print(f"ERROR: missing tables {missing}")
        return 1

    print("OK — deals.db initialized successfully")
    return 0


if __name__ == "__main__":
    sys.exit(main())
