# src/db.py

from .imports import *
engine = None
VIDEOSTABLE=None
# Build DATABASE_URL from env vars
def init_db():
    metadata.create_all(engine)

def sanitize_output(record: dict) -> dict:
    if "audio" in record:
        record["audio"] = f"<{len(record['audio'])} bytes>" if record["audio"] else None
    return record

def upsert_video(video_id: str, **fields):
    stmt = insert(VIDEOSTABLE).values(video_id=video_id, **fields)
    stmt = stmt.on_conflict_do_update(
        index_elements=["video_id"],
        set_={**fields, "updated_at": text("NOW()")}
    )
    with engine.begin() as conn:
        conn.execute(stmt)

def get_video_record(video_id: str, hide_audio: bool = True):
    with engine.begin() as conn:
        row = conn.execute(select(VIDEOSTABLE).where(VIDEOSTABLE.c.video_id == video_id)).first()
        if not row:
            return {}
        record = dict(row._mapping)
        if hide_audio and "audio" in record:
            record["audio"] = f"<{len(record['audio'])} bytes>" if record["audio"] else None
        return record or {}
    return {}
try:
    env_vars = {
        "dbname":"abstract_base",
        "user":"admin"
        }

    env_js = get_db_vars(**env_vars)

    DATABASE_URL = env_js.get("dburl")

    engine = create_engine(DATABASE_URL, future=True, pool_size=10, max_overflow=20)
    metadata = MetaData()

    VIDEOSTABLE = Table(
        "videos", metadata,
        Column("id", Integer, primary_key=True),
        Column("video_id", String, unique=True, nullable=False),
        Column("info", JSONB),
        Column("extractfields", JSONB),
        Column("rawdata", JSONB),
        Column("metadata", JSONB),
        Column("whisper", JSONB),
        Column("captions", JSONB),
        Column("thumbnails", JSONB),
        Column("total_info", JSONB),
        Column("aggregated", JSONB),
        Column("seodata", JSONB),
        Column("audio_path", String),
        Column("audio_format", String),
        Column("metatags", JSONB),
        Column("pagedata", JSONB),
        Column("created_at", TIMESTAMP, server_default=text("NOW()")),
        Column("updated_at", TIMESTAMP, server_default=text("NOW()")),
    )
    init_db()
except Exception as e:
    print(f"{e}")

# Initialize at import


def sanitize_output(record: dict) -> dict:
    if "audio" in record:
        record["audio"] = f"<{len(record['audio'])} bytes>" if record["audio"] else None
    return record

def upsert_video(video_id: str, **fields):
    """Insert or update a video record."""
    stmt = insert(VIDEOSTABLE).values(video_id=video_id, **fields)
    stmt = stmt.on_conflict_do_update(
        index_elements=["video_id"],
        set_={**fields, "updated_at": text("NOW()")}
    )
    with engine.begin() as conn:
        conn.execute(stmt)

def get_video_record(video_id: str, hide_audio: bool = True):
    with engine.begin() as conn:
        row = conn.execute(select(VIDEOSTABLE).where(VIDEOSTABLE.c.video_id == video_id)).first()
        if not row:
            return None
        record = dict(row._mapping)
        if hide_audio and "audio" in record:
            # Replace huge binary blob with a short placeholder
            record["audio"] = f"<{len(record['audio'])} bytes>" if record["audio"] else None
        return record
