#!/usr/bin/env python3
"""
endlss_pack.py - pack a folder of images/videos into a ZIP for Endlss batch upload.

WHAT THIS SCRIPT DOES (and nothing more):
  1. Looks through the folder you give it (and its sub-folders).
  2. Keeps image and video files that Endlss accepts; skips everything else,
     including hidden files and files that are too big (it tells you which).
  3. For each kept file it optionally reads two "sidecar" text files that sit
     next to it with the same name:
        holiday.jpg  ->  holiday.txt   (the description)
                          holiday.tags  (tags, separated by commas or new lines)
  4. Writes an `endlss.json` manifest describing the files.
  5. Puts the media files and endlss.json into a ZIP file you can upload on
     the Endlss upload page ("ZIP batch").
  6. Prints a summary.

PRIVACY: this script runs entirely on your computer and never connects to the
internet. It only uses Python's standard library: there is no networking code
anywhere in this file (no `socket`, `urllib`, `http`, `requests`). It reads the
folder you name and writes one ZIP file; it does not modify or delete anything.

REQUIREMENTS: Python 3.8 or newer. Nothing to install.

USAGE:
  python endlss_pack.py <folder> [-o out.zip] [--tags a,b] [--private]
                        [--collection "Name"] [--public-collection]
                        [--max-video-mb 250] [--dry-run] [--force]
  python endlss_pack.py --self-test

EXAMPLES:
  python endlss_pack.py ~/Pictures/Trip
  python endlss_pack.py ~/Pictures/Trip --collection "Trip 2026" --public-collection --tags travel,summer
  python endlss_pack.py ~/Pictures/Trip --dry-run     (just show what would happen)

Titles: you don't need to write any. Endlss turns each file name into a title
("sunset_over-the-bay.jpg" -> "sunset over the bay"). If you want a specific
title, open endlss.json afterwards and add "title": "..." to that file's entry.
"""

import argparse
import json
import os
import sys
import tempfile
import zipfile

# ─────────────────────────────────────────────────────────────────────────────
# Limits. These MUST match the Endlss website, otherwise files this script
# accepts would be rejected on upload. They come from the frontend file
# src/lib/uploadLimits.ts (IMAGE_EXTENSIONS, VIDEO_EXTENSIONS, MAX_IMAGE_SIZE,
# DEFAULT_MAX_VIDEO_UPLOAD_MB) and src/lib/zipBatch/plan.ts (MAX_ZIP_ITEMS,
# MAX_ZIP_TOTAL_BYTES). An automated test in the Endlss codebase checks that
# the numbers below stay in sync with those files.
# ─────────────────────────────────────────────────────────────────────────────
IMAGE_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp", ".gif", ".heic", ".heif"]
VIDEO_EXTENSIONS = [".mp4", ".webm", ".mov", ".avi", ".mkv"]
MAX_IMAGE_BYTES = 10 * 1024 * 1024  # 10 MB per image
DEFAULT_MAX_VIDEO_MB = 250  # per video; the site may set a different limit
MAX_ITEMS = 500  # media files per ZIP
MAX_TOTAL_BYTES = 4 * 1024 * 1024 * 1024  # 4 GB of media per ZIP

# Manifest limits (match src/lib/zipBatch/manifest.ts).
MAX_TAGS = 20
MAX_TAG_LENGTH = 50
MAX_TEXT = 2000
MAX_COLLECTION_NAME = 100

MANIFEST_NAME = "endlss.json"
MANIFEST_VERSION = 1


def human_size(n):
    """Format a byte count for people: 2048 -> '2.0 KB'."""
    for unit in ("B", "KB", "MB", "GB"):
        if n < 1024 or unit == "GB":
            return ("%d %s" % (n, unit)) if unit == "B" else ("%.1f %s" % (n, unit))
        n /= 1024.0
    return "%d B" % n


def title_from_filename(name):
    """Same rule the website uses: drop the extension, '-' and '_' become spaces."""
    stem = os.path.splitext(os.path.basename(name))[0]
    words = stem.replace("-", " ").replace("_", " ").split()
    return " ".join(words) or stem


def read_text(path):
    """Read a small sidecar text file as UTF-8 (tolerating odd bytes)."""
    with open(path, "r", encoding="utf-8", errors="replace") as fh:
        return fh.read()


def parse_tags(text):
    """'a, b\\nc' -> ['a', 'b', 'c'] (lower-case, de-duplicated, length-limited)."""
    tags = []
    for raw in text.replace("\n", ",").split(","):
        tag = raw.strip().lower()
        if tag and len(tag) <= MAX_TAG_LENGTH and tag not in tags:
            tags.append(tag)
    return tags[:MAX_TAGS]


def is_hidden(rel_path):
    """True for dotfiles / dot-folders and macOS '__MACOSX' junk."""
    parts = rel_path.replace("\\", "/").split("/")
    return any(p.startswith(".") or p == "__MACOSX" for p in parts)


def scan_folder(folder, max_video_bytes, output_path=None):
    """
    Walk `folder` and decide what to pack.

    Returns (items, skipped):
      items   - list of dicts: {"path": absolute path, "rel": path inside the ZIP,
                "size": bytes, "description": str or None, "tags": [..]}
      skipped - list of (relative path, reason) for files we left out.
    """
    items, skipped = [], []
    sidecar_exts = (".txt", ".tags")
    output_abs = os.path.abspath(output_path) if output_path else None

    for dirpath, dirnames, filenames in os.walk(folder):
        # Sort so the ZIP (and the summary) is in a predictable order.
        dirnames.sort()
        for name in sorted(filenames):
            full = os.path.join(dirpath, name)
            rel = os.path.relpath(full, folder).replace(os.sep, "/")
            ext = os.path.splitext(name)[1].lower()

            if output_abs and os.path.abspath(full) == output_abs:
                continue  # never pack the ZIP we are writing
            if is_hidden(rel):
                skipped.append((rel, "hidden or system file"))
                continue
            if ext in sidecar_exts or name == MANIFEST_NAME:
                continue  # sidecars are read below, not packed
            if ext not in IMAGE_EXTENSIONS and ext not in VIDEO_EXTENSIONS:
                skipped.append((rel, "not a supported image/video type"))
                continue

            size = os.path.getsize(full)
            limit = MAX_IMAGE_BYTES if ext in IMAGE_EXTENSIONS else max_video_bytes
            if size > limit:
                skipped.append((rel, "too large (%s, max %s)" % (human_size(size), human_size(limit))))
                continue

            # Optional sidecars: same name, .txt (description) / .tags (tags).
            stem = os.path.splitext(full)[0]
            description, tags = None, []
            if os.path.isfile(stem + ".txt"):
                description = read_text(stem + ".txt").strip()[:MAX_TEXT] or None
            if os.path.isfile(stem + ".tags"):
                tags = parse_tags(read_text(stem + ".tags"))

            items.append({"path": full, "rel": rel, "size": size, "description": description, "tags": tags})
    return items, skipped


def build_manifest(items, tags=None, private=False, collection=None, public_collection=False):
    """Create the endlss.json content (version 1). See endlss.schema.json."""
    defaults = {
        "tags": tags or [],
        "isPrivate": bool(private),
        "collection": (
            {"name": collection[:MAX_COLLECTION_NAME], "isPublic": bool(public_collection)} if collection else None
        ),
        "description": None,
    }
    entries = []
    for it in items:
        entry = {"file": it["rel"]}
        # No "title": the website derives it from the file name, and leaves it
        # editable by Endlss' automatic tagging. Add one by hand to fix it.
        if it["description"]:
            entry["description"] = it["description"]
        if it["tags"]:
            entry["tags"] = it["tags"]
        entries.append(entry)
    return {"version": MANIFEST_VERSION, "defaults": defaults, "items": entries}


def write_zip(out_path, items, manifest):
    """
    Write the ZIP. Media is STORED (not re-compressed): photos and videos are
    already compressed, and stored entries let the website read each file
    straight out of the ZIP without unpacking it into memory (important on
    phones). The small endlss.json is compressed normally.
    allowZip64=False keeps the ZIP in the classic format the website reads.
    """
    with zipfile.ZipFile(out_path, "w", allowZip64=False) as zf:
        zf.writestr(
            zipfile.ZipInfo(MANIFEST_NAME, date_time=(2020, 1, 1, 0, 0, 0)),
            json.dumps(manifest, indent=2, ensure_ascii=False),
            compress_type=zipfile.ZIP_DEFLATED,
        )
        for it in items:
            zf.write(it["path"], arcname=it["rel"], compress_type=zipfile.ZIP_STORED)


def pack(folder, out_path, tags=None, private=False, collection=None, public_collection=False,
         max_video_mb=DEFAULT_MAX_VIDEO_MB, dry_run=False, force=False, log=print):
    """Do the whole job. Returns 0 on success, a non-zero exit code otherwise."""
    if not os.path.isdir(folder):
        log("Error: %s is not a folder." % folder)
        return 2
    if not dry_run and os.path.exists(out_path) and not force:
        log("Error: %s already exists. Choose another name with -o, or add --force to replace it." % out_path)
        return 2

    items, skipped = scan_folder(folder, max_video_mb * 1024 * 1024, out_path)
    total = sum(it["size"] for it in items)

    log("Folder:   %s" % os.path.abspath(folder))
    log("Media:    %d file(s), %s" % (len(items), human_size(total)))
    for rel, reason in skipped:
        log("  skipped %s - %s" % (rel, reason))
    with_desc = sum(1 for it in items if it["description"])
    with_tags = sum(1 for it in items if it["tags"])
    log("Sidecars: %d description(s), %d tag list(s)" % (with_desc, with_tags))
    if collection:
        log("Collection: %s (%s)" % (collection, "public" if public_collection else "private"))
    if tags:
        log("Tags for every file: %s" % ", ".join(tags))
    if private:
        log("Uploads will be private (only you can see them).")

    if not items:
        log("Error: no supported image or video files found.")
        return 1
    if len(items) > MAX_ITEMS:
        log("Error: %d files is more than the %d allowed in one ZIP. Split the folder and run again." % (len(items), MAX_ITEMS))
        return 1
    if total > MAX_TOTAL_BYTES:
        log("Error: %s is more than the %s allowed in one ZIP. Split the folder and run again."
            % (human_size(total), human_size(MAX_TOTAL_BYTES)))
        return 1

    manifest = build_manifest(items, tags, private, collection, public_collection)
    if dry_run:
        log("Dry run: nothing written. First files and their titles:")
        for it in items[:10]:
            log("  %s  ->  \"%s\"" % (it["rel"], title_from_filename(it["rel"])))
        return 0

    write_zip(out_path, items, manifest)
    log("Wrote:    %s (%s)" % (os.path.abspath(out_path), human_size(os.path.getsize(out_path))))
    log("Next: open the Endlss upload page, choose \"ZIP batch\" and pick this file.")
    return 0


# ─────────────────────────────────────────────────────────────────────────────
# Self-test: builds a throw-away folder in your temp directory, packs it and
# checks the result. Run with:  python endlss_pack.py --self-test
# ─────────────────────────────────────────────────────────────────────────────
def self_test():
    quiet = lambda *_a, **_k: None  # noqa: E731 - silence pack() output
    with tempfile.TemporaryDirectory() as tmp:
        src = os.path.join(tmp, "My Trip")
        os.makedirs(os.path.join(src, "day 2"))
        os.makedirs(os.path.join(src, ".git"))

        def touch(rel, data=b"x"):
            with open(os.path.join(src, rel), "wb") as fh:
                fh.write(data)

        touch("sunset_over-the-bay.jpg", b"\xff\xd8" + b"0" * 100)
        touch("sunset_over-the-bay.txt", "Golden hour\n".encode("utf-8"))
        touch("sunset_over-the-bay.tags", b"Sky, sea\ngold, sky")
        touch("day 2/clip.MP4", b"v" * 50)
        touch("notes.pdf")
        touch(".DS_Store")
        touch(".git/config")
        touch("huge.png", b"0" * (MAX_IMAGE_BYTES + 1))
        touch("big-video.mov", b"0" * (1024 * 1024 + 1))  # over a 1 MB video limit below

        out = os.path.join(tmp, "out.zip")
        assert pack(src, out, dry_run=True, max_video_mb=1, log=quiet) == 0
        assert not os.path.exists(out), "dry run must not write"

        rc = pack(src, out, tags=["travel"], private=True, collection="Trip", public_collection=True,
                  max_video_mb=1, log=quiet)
        assert rc == 0, rc
        assert pack(src, out, max_video_mb=1, log=quiet) == 2, "must refuse to overwrite without --force"

        with zipfile.ZipFile(out) as zf:
            names = sorted(zf.namelist())
            assert names == ["day 2/clip.MP4", "endlss.json", "sunset_over-the-bay.jpg"], names
            for info in zf.infolist():
                expected = zipfile.ZIP_DEFLATED if info.filename == MANIFEST_NAME else zipfile.ZIP_STORED
                assert info.compress_type == expected, (info.filename, info.compress_type)
            manifest = json.loads(zf.read(MANIFEST_NAME).decode("utf-8"))

        assert manifest["version"] == 1
        assert manifest["defaults"] == {
            "tags": ["travel"],
            "isPrivate": True,
            "collection": {"name": "Trip", "isPublic": True},
            "description": None,
        }, manifest["defaults"]
        by_file = {e["file"]: e for e in manifest["items"]}
        assert by_file["sunset_over-the-bay.jpg"] == {
            "file": "sunset_over-the-bay.jpg",
            "description": "Golden hour",
            "tags": ["sky", "sea", "gold"],
        }, by_file
        assert by_file["day 2/clip.MP4"] == {"file": "day 2/clip.MP4"}
        assert title_from_filename("day 2/sunset_over-the-bay.jpg") == "sunset over the bay"

        # Empty folder -> error code, no ZIP.
        empty = os.path.join(tmp, "empty")
        os.makedirs(empty)
        assert pack(empty, os.path.join(tmp, "e.zip"), log=quiet) == 1

    print("self-test OK")
    return 0


def main(argv=None):
    parser = argparse.ArgumentParser(
        description="Pack a folder of images/videos into a ZIP for Endlss batch upload. "
        "Runs entirely on your computer; never connects to the internet.",
    )
    parser.add_argument("folder", nargs="?", help="the folder to pack")
    parser.add_argument("-o", "--output", help="ZIP file to write (default: <folder>.zip next to the folder)")
    parser.add_argument("--tags", default="", help="comma-separated tags added to every file, e.g. travel,summer")
    parser.add_argument("--private", action="store_true", help="make every upload private (only you see them)")
    parser.add_argument("--collection", help="put every upload into a NEW collection with this name")
    parser.add_argument("--public-collection", action="store_true", help="make that new collection public")
    parser.add_argument("--max-video-mb", type=int, default=DEFAULT_MAX_VIDEO_MB,
                        help="largest video to include, in MB (default %d)" % DEFAULT_MAX_VIDEO_MB)
    parser.add_argument("--dry-run", action="store_true", help="show what would be packed; write nothing")
    parser.add_argument("--force", action="store_true", help="replace the output ZIP if it already exists")
    parser.add_argument("--self-test", action="store_true", help="run the built-in self-test and exit")
    args = parser.parse_args(argv)

    if args.self_test:
        return self_test()
    if not args.folder:
        parser.print_help()
        return 2

    folder = os.path.normpath(args.folder)
    out = args.output or (folder.rstrip("/\\") + ".zip")
    return pack(
        folder,
        out,
        tags=parse_tags(args.tags),
        private=args.private,
        collection=(args.collection or "").strip() or None,
        public_collection=args.public_collection,
        max_video_mb=args.max_video_mb,
        dry_run=args.dry_run,
        force=args.force,
    )


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