"""End-to-end guard: upload a driver through the HTTP endpoint, then export
a NinjaRMM package from the resulting Driver record. This prevents regressions
where DriverStore save path and packages.py driver lookup path diverge."""
import io
import json
import zipfile

import pytest


@pytest.fixture
def driver_zip_bytes():
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr("printer.inf", "[Version]\nSignature=$WINDOWS NT$\n")
        zf.writestr("printer.cat", "FAKE_CAT")
    return buf.getvalue()


def test_upload_then_ninja_export_finds_driver_on_disk(
    client, tmp_data_dir, driver_zip_bytes
):
    from imptune.db.models import Client, Driver, Printer

    upload_resp = client.post(
        "/drivers/upload",
        files={"file": ("printer_driver.zip", driver_zip_bytes, "application/zip")},
    )
    assert upload_resp.status_code == 200

    driver = Driver.select().order_by(Driver.id.desc()).first()
    assert driver is not None
    driver.driver_desc = json.dumps(["HP LaserJet Pro"])
    driver.save()

    tenant = Client.create(name="Acme Corp")
    printer = Printer.create(
        name="Round Trip Printer",
        ip_address="192.168.1.50",
        port_name="IP_192.168.1.50",
        client=tenant,
        driver=driver,
    )

    resp = client.get(f"/printers/{printer.id}/packages/ninja")
    assert resp.status_code == 200, resp.text
    assert resp.headers["content-type"] == "application/zip"

    out = zipfile.ZipFile(io.BytesIO(resp.content))
    names = out.namelist()
    assert any(n.endswith("install.ps1") for n in names)
    assert any("drivers/printer.inf" in n for n in names)
