from __future__ import annotations

import pytest

from granule.ingest.youtube import ingest_youtube
from granule.config import settings


class Boom(Exception):
    pass


def test_ingest_youtube_error_metadata(monkeypatch):
    # Force debug for logging path (not strictly asserted but ensures branch executed)
    monkeypatch.setattr(settings, "debug", True, raising=False)

    # Patch internal _fetch_transcript to raise generic exception
    import granule.ingest.youtube as yt
    monkeypatch.setattr(yt, "_fetch_transcript", lambda vid, retries=2, delay=0.1: (_ for _ in ()).throw(Boom("net fail")))

    doc = ingest_youtube("https://www.youtube.com/watch?v=FAKEID12345")
    assert doc.text.startswith("[NO TRANSCRIPT AVAILABLE for")
    assert "ingest_error" in doc.extras
    err = doc.extras["ingest_error"]
    assert err["type"] == "Boom"
    assert err["stage"] == "unexpected"
    assert "net fail" in err["message"]
