# src/db.py

# src/db.py
from .imports import *

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()")),
)

def init_db():
    metadata.create_all(engine)

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

def upsert_video(video_id, **fields):
    video_id = normalize_video_id(video_id)

    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, hide_audio: bool = True):
    video_id = normalize_video_id(video_id)

    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)
    return sanitize_output(record) if hide_audio else record

# Initialize at import
init_db()

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
