#!/usr/bin/env python3
"""
Simple HEIC -> PDF converter using Pillow + pillow-heif.
Usage: convert_heic_to_pdf.py input.heic output.pdf
"""
import sys
from pathlib import Path

def fail(msg, code=1):
    print(msg, file=sys.stderr)
    sys.exit(code)

try:
    from PIL import Image
    import pillow_heif
except Exception as e:
    fail(f"MISSING_DEP {e}")


def convert(in_path, out_path):
    in_p = Path(in_path)
    out_p = Path(out_path)
    if not in_p.exists():
        fail(f"INPUT_NOT_FOUND {in_path}", code=3)
    heif = pillow_heif.read_heif(in_p)
    img = Image.frombytes(heif.mode, heif.size, heif.data, "raw")
    # Save as single-page PDF
    img.save(out_p, "PDF", resolution=150.0)
    return 0


def main():
    if len(sys.argv) < 3:
        fail("Usage: convert_heic_to_pdf.py <input.heic> <output.pdf>")
    try:
        rc = convert(sys.argv[1], sys.argv[2])
    except Exception as e:
        fail(f"CONVERT_ERROR {e}")
    sys.exit(rc)


if __name__ == '__main__':
    main()
#!/usr/bin/env python3
"""
convert_heic_to_pdf.py
Converts a HEIC/HEIF image to PDF using Pillow + pillow-heif.
Usage:
  python convert_heic_to_pdf.py /path/to/input.heic /path/to/output.pdf
"""
import sys
from pathlib import Path

try:
    from PIL import Image
    from pillow_heif import register_heif_opener
except Exception as exc:
    print("MISSING_DEP", exc)
    raise


def convert(heic_path: Path, pdf_path: Path) -> None:
    register_heif_opener()
    with Image.open(heic_path) as img:
        frames = []
        if getattr(img, "is_animated", False) and getattr(img, "n_frames", 1) > 1:
            for i in range(img.n_frames):
                img.seek(i)
                frames.append(img.convert("RGB"))
        else:
            frames.append(img.convert("RGB"))

        first, *rest = frames
        first.save(pdf_path, "PDF", save_all=bool(rest), append_images=rest)


def main() -> int:
    if len(sys.argv) < 3:
        print("Usage: convert_heic_to_pdf.py input.heic output.pdf")
        return 2
    heic_path = Path(sys.argv[1])
    pdf_path = Path(sys.argv[2])

    if not heic_path.exists():
        print("Input HEIC not found:", heic_path)
        return 3

    try:
        convert(heic_path, pdf_path)
        print("OK", pdf_path)
        return 0
    except Exception as exc:
        print("ERROR", exc)
        return 1


if __name__ == "__main__":
    sys.exit(main())
