#!/usr/bin/env python3
"""Generates tiny, real media files under public/mock-media/ so mock-mode
previews and downloads genuinely work (image/pdf/audio/video office files)."""
import os, struct, wave, zipfile, zlib

OUT = os.path.join(os.path.dirname(__file__), "..", "public", "mock-media")
os.makedirs(OUT, exist_ok=True)


def png(path, w, h, rgb_top, rgb_bottom):
    # vertical two-tone gradient PNG
    raw = b""
    for y in range(h):
        raw += b"\x00"
        t = y / max(h - 1, 1)
        r = int(rgb_top[0] + (rgb_bottom[0] - rgb_top[0]) * t)
        g = int(rgb_top[1] + (rgb_bottom[1] - rgb_top[1]) * t)
        b = int(rgb_top[2] + (rgb_bottom[2] - rgb_top[2]) * t)
        raw += bytes([r, g, b]) * w

    def chunk(typ, data):
        c = struct.pack(">I", len(data)) + typ + data
        return c + struct.pack(">I", zlib.crc32(typ + data) & 0xFFFFFFFF)

    ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
    data = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
    with open(os.path.join(OUT, path), "wb") as f:
        f.write(data)


def pdf(path, title, lines):
    def esc(s):
        return s.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")

    content = "BT /F1 20 Tf 72 740 Td (%s) Tj ET\n" % esc(title)
    y = 700
    for ln in lines:
        content += "BT /F1 12 Tf 72 %d Td (%s) Tj ET\n" % (y, esc(ln))
        y -= 18
    objects = []
    objects.append("<< /Type /Catalog /Pages 2 0 R >>")
    objects.append("<< /Type /Pages /Kids [3 0 R] /Count 1 >>")
    objects.append("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>")
    objects.append("<< /Length %d >>\nstream\n%s\nendstream" % (len(content), content))
    objects.append("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
    out = "%PDF-1.4\n"
    offsets = []
    for i, obj in enumerate(objects):
        offsets.append(len(out.encode()))
        out += "%d 0 obj\n%s\nendobj\n" % (i + 1, obj)
    xref_pos = len(out.encode())
    out += "xref\n0 %d\n0000000000 65535 f \n" % (len(objects) + 1)
    for off in offsets:
        out += "%010d 00000 n \n" % off
    out += "trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF" % (len(objects) + 1, xref_pos)
    with open(os.path.join(OUT, path), "wb") as f:
        f.write(out.encode())


def wav(path, seconds=0.5, freq=8000):
    frames = int(seconds * freq)
    silence = b"\x80" * frames  # 8-bit unsigned silence
    with wave.open(os.path.join(OUT, path), "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(1)
        w.setframerate(freq)
        w.writeframes(silence)


def box(typ, payload):
    return struct.pack(">I", len(payload) + 8) + typ + payload


def mp4(path):
    matrix = struct.pack(">9I", 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000)
    ftyp = box(b"ftyp", b"isom" + struct.pack(">I", 512) + b"isomiso2avc1mp41")
    mvhd = box(b"mvhd", struct.pack(">4I", 0, 0, 0, 1000) + struct.pack(">I", 1000)
               + struct.pack(">I", 0x00010000) + struct.pack(">H", 0x0100) + b"\x00\x00"
               + b"\x00" * 10 + matrix + b"\x00" * 24 + struct.pack(">I", 2))
    tkhd = box(b"tkhd", struct.pack(">I", 7) + struct.pack(">4I", 0, 0, 1, 0)
               + struct.pack(">I", 1000) + b"\x00" * 8 + struct.pack(">h", 0) * 2
               + struct.pack(">h", 0) + b"\x00\x00" + matrix
               + struct.pack(">I", 640 << 16) + struct.pack(">I", 360 << 16))
    mdhd = box(b"mdhd", struct.pack(">4I", 0, 0, 0, 1000) + struct.pack(">I", 1000)
               + struct.pack(">H", 0x55C4) + struct.pack(">H", 0))
    hdlr = box(b"hdlr", struct.pack(">I", 0) + b"\x00" * 4 + b"vide" + b"\x00" * 12 + b"VideoHandler\x00")
    vmhd = box(b"vmhd", struct.pack(">I", 1) + b"\x00" * 8)
    url_box = box(b"url ", struct.pack(">I", 1))
    dref = box(b"dref", struct.pack(">I", 0) + struct.pack(">I", 1) + url_box)
    dinf = box(b"dinf", dref)
    avc1_payload = (b"\x00" * 6 + struct.pack(">H", 1) + b"\x00" * 16
                    + struct.pack(">H", 640) + struct.pack(">H", 360)
                    + struct.pack(">I", 0x00480000) * 2 + b"\x00" * 4 + struct.pack(">H", 1)
                    + b"\x00" * 32 + struct.pack(">h", 0x0018) + struct.pack(">h", -1))
    stsd = box(b"stsd", struct.pack(">I", 0) + struct.pack(">I", 1) + box(b"avc1", avc1_payload))
    stts = box(b"stts", struct.pack(">I", 0) + struct.pack(">I", 0))
    stsc = box(b"stsc", struct.pack(">I", 0) + struct.pack(">I", 0))
    stsz = box(b"stsz", struct.pack(">I", 0) + struct.pack(">2I", 0, 0))
    stco = box(b"stco", struct.pack(">I", 0) + struct.pack(">I", 0))
    stbl = box(b"stbl", stsd + stts + stsc + stsz + stco)
    minf = box(b"minf", vmhd + dinf + stbl)
    mdia = box(b"mdia", mdhd + hdlr + minf)
    trak = box(b"trak", tkhd + mdia)
    moov = box(b"moov", mvhd + trak)
    mdat = box(b"mdat", b"")
    with open(os.path.join(OUT, path), "wb") as f:
        f.write(ftyp + moov + mdat)


def docx(path):
    with zipfile.ZipFile(os.path.join(OUT, path), "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("[Content_Types].xml",
                   '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
                   '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
                   '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
                   '<Default Extension="xml" ContentType="application/xml"/>'
                   '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'
                   "</Types>")
        z.writestr("_rels/.rels",
                   '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
                   '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
                   '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>'
                   "</Relationships>")
        z.writestr("word/document.xml",
                   '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
                   '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>'
                   "<w:p><w:r><w:t>Quarterly report — archived sample document.</w:t></w:r></w:p>"
                   "</w:body></w:document>")


def xlsx(path):
    with zipfile.ZipFile(os.path.join(OUT, path), "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("[Content_Types].xml",
                   '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
                   '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
                   '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
                   '<Default Extension="xml" ContentType="application/xml"/>'
                   '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
                   '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
                   "</Types>")
        z.writestr("_rels/.rels",
                   '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
                   '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
                   '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
                   "</Relationships>")
        z.writestr("xl/workbook.xml",
                   '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
                   '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
                   'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
                   '<sheets><sheet name="Sales" sheetId="1" r:id="rId1"/></sheets></workbook>')
        z.writestr("xl/_rels/workbook.xml.rels",
                   '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
                   '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
                   '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>'
                   "</Relationships>")
        z.writestr("xl/worksheets/sheet1.xml",
                   '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
                   '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
                   "<sheetData>"
                   '<row r="1"><c r="A1" t="inlineStr"><is><t>Month</t></is></c><c r="B1" t="inlineStr"><is><t>Total</t></is></c></row>'
                   '<row r="2"><c r="A2" t="inlineStr"><is><t>August</t></is></c><c r="B2"><v>18450</v></c></row>'
                   "</sheetData></worksheet>")


def plain_zip(path):
    with zipfile.ZipFile(os.path.join(OUT, path), "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("readme.txt", "Presentation files bundle (archived sample).\n")
        z.writestr("slides/slide-notes.txt", "Slide speaker notes placeholder.\n")


png("product-photo.png", 96, 64, (37, 99, 235), (14, 165, 233))
png("menu-photo.png", 96, 64, (22, 163, 74), (21, 128, 61))
png("sara-photo.png", 96, 64, (124, 58, 237), (91, 33, 182))
png("floor-plan.png", 96, 64, (234, 88, 12), (194, 65, 12))
png("banner.png", 96, 64, (219, 39, 119), (157, 23, 77))
png("sticker.png", 32, 32, (250, 204, 21), (245, 158, 11))
pdf("invoice.pdf", "Invoice INV-2026-0091", ["Customer: Ahmed Samy", "Amount: USD 460.00", "Status: PAID", "Issued by Sales Line (archived sample file)."])
pdf("catalog.pdf", "Product Catalog 2026", ["Industrial parts & accessories", "Section A: Fasteners", "Section B: Bearings", "Archived sample file."])
docx("quarterly-report.docx")
xlsx("sales-data.xlsx")
plain_zip("presentation-files.zip")
mp4("promo.mp4")
wav("voice-note.wav", seconds=1.0)
print("mock-media generated:", sorted(os.listdir(OUT)))
