"""Match JPG gallery favorites to existing camera originals without reading image pixels."""
import argparse
import csv
import io
import json
import os
from pathlib import Path
import tempfile

RAW = set("3fr arw cr2 cr3 crw dng erf fff iiq kdc mef mos mrw nef nrw orf pef raf raw rw2 rwl sr2 srf srw x3f".split())


def picks_from(path):
    if path.stat().st_size > 2_000_000:
        raise ValueError("Use a favorites list smaller than 2 MB.")
    rows = [row for row in csv.reader(io.StringIO(path.read_text(encoding="utf-8-sig")), strict=True) if any(v.strip() for v in row)]
    if not rows:
        raise ValueError("The favorites list is empty.")
    header = [v.strip().lower() for v in rows[0]]
    if header in (["favorite"], ["favorite", "original"]):
        picks = []
        for row in rows[1:]:
            if len(row) != len(header):
                raise ValueError("Each CSV row must have the same columns as its header.")
            picks.append((row[0].strip(), row[1].strip() if len(row) == 2 else ""))
    else:
        # Pixieset's comma-separated Lightroom list and one-filename-per-line lists.
        picks = [(cell.strip(), "") for row in rows for cell in row if cell.strip()]
    if not picks:
        raise ValueError("Include at least one favorite.")
    for name, original in picks:
        if not name or "/" in name or "\\" in name:
            raise ValueError("Put a gallery filename in favorite and its optional relative path in original.")
        for value in (name, original):
            if value and (value[0] in "=+@-" or any(ord(ch) < 32 for ch in value)):
                raise ValueError("A favorite contains a control character or spreadsheet formula prefix. Review its name before exporting a CSV.")
    return picks


def camera_inventory(root):
    found = {}
    def raise_scan_error(error):
        raise error

    for directory, _, names in os.walk(root, onerror=raise_scan_error):
        for name in names:
            path = Path(directory) / name
            if path.suffix.lower()[1:] not in RAW or path.is_symlink() or not path.is_file():
                continue
            found.setdefault(path.stem.casefold(), []).append(path.relative_to(root).as_posix())
    for candidates in found.values():
        candidates.sort()
    return found


def match(picks, inventory):
    report = []
    for sequence, (favorite, override) in enumerate(picks, 1):
        suffix = Path(favorite).suffix.lower()
        stem = Path(favorite).stem if suffix in (".jpeg", ".jpg") or suffix[1:] in RAW else favorite
        candidates = inventory.get(stem.casefold(), [])
        chosen = ""
        if override:
            if override in candidates:
                status, chosen = "confirmed", override
            else:
                status = "check chosen path"
        elif not candidates:
            status = "missing"
        elif len(candidates) > 1:
            status = "ambiguous"
        else:
            status, chosen = "matched", candidates[0]
        report.append((sequence, favorite, status, chosen, candidates))
    return report


def export(root, output_root, report):
    selected = list(dict.fromkeys(row[3] for row in report if row[3]))
    all_resolved = all(row[3] for row in report)
    for relative in selected:
        if relative[0] in "=+@-" or any(ord(ch) < 32 for ch in relative):
            raise ValueError("An original path contains a control character or formula prefix. Review it before exporting a CSV.")
    output_root.mkdir(parents=True, exist_ok=True)
    folder = Path(tempfile.mkdtemp(prefix="picks-", dir=output_root))
    with (folder / "review.csv").open("w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["pick", "favorite", "status", "original", "candidates"])
        for seq, name, status, chosen, candidates in report:
            writer.writerow([seq, name, status, chosen, json.dumps(candidates, ensure_ascii=False)])
    with (folder / "resolve.csv").open("w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["favorite", "original"])
        writer.writerows((row[1], row[3]) for row in report)
    print("Local review folder:", folder)
    if not all_resolved:
        print("Some picks need review. Correct resolve.csv and run it again. No collection was created.")
        return
    paths = [str(root / relative) for relative in selected]
    if any('"' in p or "\\" in p or "\n" in p or "\r" in p for p in paths):
        print("The CSV is ready. This collection writer supports POSIX paths without double quotes, backslashes or line breaks.")
        return
    with (folder / "retouch.gqv").open("w", encoding="utf-8", newline="\n") as handle:
        handle.write("#Geeqie collection\n")
        for path in paths:
            handle.write('"' + path + '"\n')
        handle.write("#end\n")
    print("Open retouch.gqv in Geeqie on this machine. Collection contains", len(selected), "unique originals.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("favorites", type=Path, help="Local CSV or JPG filename list")
    parser.add_argument("originals", type=Path, help="Parent of the shoot folders")
    parser.add_argument("--out", type=Path, default=Path("reviews"), help="Directory for new private review folders")
    args = parser.parse_args()
    try:
        root = args.originals.resolve(strict=True)
        if not root.is_dir():
            raise ValueError("Choose a folder containing your camera originals.")
        export(root, args.out, match(picks_from(args.favorites), camera_inventory(root)))
    except (OSError, UnicodeError, ValueError, csv.Error) as error:
        parser.exit(2, str(error) + "\n")


if __name__ == "__main__":
    main()
