import io, os, tempfile, zipfile, sys
from fastapi.testclient import TestClient


def _client(monkeypatch):
    # Insert web-backend root (3 levels up from this file) so _shared is importable
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    from app import config, db
    tmp = tempfile.mkdtemp()
    monkeypatch.setattr(config, "INSTA_DATA_PATH", tmp, raising=False)
    monkeypatch.setattr(db, "DB_PATH", os.path.join(tmp, "insta.db"), raising=False)
    db.init_db()
    from app.main import app
    return TestClient(app), db, tmp


def test_package_zip_contains_pngs_and_caption(monkeypatch):
    client, db, tmp = _client(monkeypatch)
    # 슬레이트 + 2개 asset(실제 PNG 파일) 시드
    sid = db.add_card_slate({
        "keyword": "k",
        "category": "economy",
        "status": "rendered",
        "cover_copy": {"headline": "h"},
        "body_copies": [{"headline": "b", "body": "x"}] * 8,
        "cta_copy": {},
        "suggested_caption": "캡션입니다",
        "hashtags": ["#a", "#b"],
    })
    cards_dir = os.path.join(tmp, "insta_cards", str(sid))
    os.makedirs(cards_dir, exist_ok=True)
    for pg in (1, 2):
        fp = os.path.join(cards_dir, f"{pg:02d}.png")
        with open(fp, "wb") as f:
            f.write(b"\x89PNG\r\n" + b"0" * 2000)
        db.add_card_asset(slate_id=sid, page_index=pg, file_path=fp)
    r = client.get(f"/api/insta/slates/{sid}/package")
    assert r.status_code == 200
    assert r.headers["content-type"] == "application/zip"
    z = zipfile.ZipFile(io.BytesIO(r.content))
    names = z.namelist()
    assert any(n.endswith(".png") for n in names)
    assert "caption.txt" in names
    cap = z.read("caption.txt").decode("utf-8")
    assert "캡션입니다" in cap and "#a" in cap


def test_package_unknown_slate_404(monkeypatch):
    client, db, tmp = _client(monkeypatch)
    r = client.get("/api/insta/slates/999999/package")
    assert r.status_code == 404


def test_package_no_assets_409(monkeypatch):
    client, db, tmp = _client(monkeypatch)
    sid = db.add_card_slate({
        "keyword": "k",
        "category": "economy",
        "status": "draft",
        "cover_copy": {"headline": "h"},
        "body_copies": [{"headline": "b", "body": "x"}] * 8,
        "cta_copy": {},
        "suggested_caption": "c",
        "hashtags": [],
    })
    r = client.get(f"/api/insta/slates/{sid}/package")
    assert r.status_code == 409
