#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
D53 · 赛博游园会新玩法真实实操 —— EXIF 读取 / 方向应用 / 全量去元数据 → 无损 PNG

本地依赖 (版本清晰):
  * Python 3.14.2          —— 仅用标准库: struct, zlib, hashlib, subprocess,
                               argparse, os, sys, json, binascii
  * libjpeg-turbo 3.2.1    —— 仅用其 djpeg 工具做 JPEG 解码为 PPM。
                               djpeg 只解像素、不读取也不应用 EXIF 方向，
                               因此解码结果就是“存储方向”的原始像素。

工作流 (严格按 spec.json 的 orientationRule):
  1) 解析输入 JPEG 的 APP0/APP1(Exif) 段与 TIFF/IFD → 取全部字段 + Orientation。
  2) 用 djpeg 把 JPEG 解码成 PPM (存储方向原始像素)。
  3) 按 EXIF Orientation 把方向“烘焙”进像素 (视觉内容与浏览器自动转正后一致)。
  4) 重新编码为纯 PNG，只写 IHDR/IDAT/IEND，绝不写任何元数据块
     (eXIf/tEXt/iTXt/zTXt/gAMA/sRGB/... 全部不存在)。
  5) 不覆盖原件；不覆盖已存在的输出文件 (除非显式 --force)。

用法:
  python3 clean_exif.py                 # 默认 ../inputs/synthetic-location.jpg -> ./synthetic-location.png
  python3 clean_exif.py <in> <out>
  python3 clean_exif.py --before        # 只打印原件 EXIF 字段，不写任何文件
  python3 clean_exif.py --selftest      # 校验 8 种 Orientation 变换的单元测试

相对路径: 所有默认路径都基于本脚本所在目录 (outputs/) 解析，与调用时的 CWD 无关。
"""

import argparse
import binascii
import hashlib
import json
import os
import struct
import subprocess
import sys
import zlib

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_INPUT = os.path.normpath(os.path.join(SCRIPT_DIR, "..", "inputs", "synthetic-location.jpg"))
DEFAULT_OUTPUT = os.path.join(SCRIPT_DIR, "synthetic-location.png")


# ----------------------------------------------------------------------------
# EXIF / TIFF 解析 (纯标准库)
# ----------------------------------------------------------------------------
TYPE_SIZE = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8, 11: 4, 12: 8}
TYPE_NAME = {1: "BYTE", 2: "ASCII", 3: "SHORT", 4: "LONG", 5: "RATIONAL",
             7: "UNDEFINED", 9: "SLONG", 10: "SRATIONAL", 11: "FLOAT", 12: "DOUBLE"}

IFD0_TAGS = {
    0x010E: "ImageDescription", 0x010F: "Make", 0x0110: "Model", 0x0112: "Orientation",
    0x011A: "XResolution", 0x011B: "YResolution", 0x0128: "ResolutionUnit",
    0x0131: "Software", 0x0132: "DateTime", 0x013B: "Artist", 0x0213: "YCbCrPositioning",
    0x8298: "Copyright", 0x8769: "ExifIFDPointer", 0x8825: "GPSIFDPointer",
}
EXIF_TAGS = {
    0x829A: "ExposureTime", 0x829D: "FNumber", 0x9000: "ExifVersion",
    0x9003: "DateTimeOriginal", 0x9004: "DateTimeDigitized", 0x9101: "ComponentsConfiguration",
    0x9201: "ShutterSpeedValue", 0x9209: "Flash", 0x927C: "MakerNote",
    0x9286: "UserComment", 0x9291: "SubSecTimeOriginal", 0xA000: "FlashpixVersion",
    0xA001: "ColorSpace", 0xA002: "PixelXDimension", 0xA003: "PixelYDimension",
}
GPS_TAGS = {
    0x0000: "GPSVersionID", 0x0001: "GPSLatitudeRef", 0x0002: "GPSLatitude",
    0x0003: "GPSLongitudeRef", 0x0004: "GPSLongitude", 0x0005: "GPSAltitudeRef",
    0x0006: "GPSAltitude", 0x0007: "GPSTimeStamp", 0x000D: "GPSImgDirectionRef",
    0x000E: "GPSImgDirection", 0x0012: "GPSMapDatum", 0x001D: "GPSDateStamp",
    0x001B: "GPSProcessingMethod", 0x001A: "GPSDestBearingRef", 0x001B: "GPSDestBearing",
}


def _u(v, bo):
    return struct.unpack_from(bo + "H", v, 0)[0]


def _fmt_rationals(raw, bo):
    out = []
    for i in range(0, len(raw), 8):
        n, d = struct.unpack_from(bo + "II", raw, i)
        if d != 0:
            out.append(f"{n}/{d}")
        else:
            out.append(f"{n}/0")
    return ", ".join(out)


def _fmt_gps(dms_raw, bo):
    """三组 RATIONAL (deg, min, sec) → 度数值与 DMS 字符串。"""
    parts = []
    for i in range(0, len(dms_raw), 8):
        n, d = struct.unpack_from(bo + "II", dms_raw, i)
        parts.append(n / d if d else 0.0)
    deg, mn, sc = parts
    decimal = deg + mn / 60.0 + sc / 3600.0
    return decimal, f"{int(deg)}°{int(mn)}'{round(sc, 4):g}\""


def parse_exif(path):
    """解析 JPEG 的 APP1 Exif 段，返回 (orientation:int, fields:list[dict])。"""
    data = open(path, "rb").read()

    # 遍历 JPEG 段
    i = 2  # 跳过 SOI (FFD8)
    app0 = None
    app1_payload = None
    app1_start = None
    app1_len = None
    while i + 4 <= len(data):
        if data[i] != 0xFF:
            raise ValueError(f"非 JPEG 段起始 @ {i:#x}")
        marker = data[i + 1]
        if marker == 0xDA:  # SOS: 之后是熵编码图像数据，不再有段结构
            break
        if marker in (0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
            i += 2
            continue
        seg_len = struct.unpack_from(">H", data, i + 2)[0]
        payload_start = i + 4
        if marker == 0xE0:
            app0 = data[payload_start: payload_start + seg_len - 2]
        if marker == 0xE1 and data[payload_start:payload_start + 6] == b"Exif\x00\x00":
            app1_start = payload_start + 6
            app1_len = seg_len - 2 - 6
            app1_payload = data[app1_start: app1_start + app1_len]
        i += 2 + seg_len

    if app1_payload is None:
        raise ValueError("未找到 APP1 Exif 段")

    tiff = app1_payload
    bo = ">" if tiff[:2] == b"MM" else "<"
    if struct.unpack_from(bo + "H", tiff, 2)[0] != 0x002A:
        raise ValueError("TIFF magic 不符")

    def read_bytes_from(value_off, length):
        return data[app1_start + value_off: app1_start + value_off + length]

    def parse_ifd(off):
        n = struct.unpack_from(bo + "H", tiff, off)[0]
        entries = []
        for k in range(n):
            eo = off + 2 + k * 12
            tag, typ, cnt = struct.unpack_from(bo + "HHI", tiff, eo)
            size = TYPE_SIZE.get(typ, 1) * cnt
            if size <= 4:
                raw = tiff[eo + 8: eo + 12][:size]
            else:
                val_off = struct.unpack_from(bo + "I", tiff, eo + 8)[0]
                raw = read_bytes_from(val_off, size)
            entries.append((tag, typ, cnt, raw))
        nxt = struct.unpack_from(bo + "I", tiff, off + 2 + n * 12)[0]
        return entries, nxt

    fields = []
    orientation = 1

    def emit(tagnames, tag, typ, cnt, raw, ifd_name):
        nonlocal orientation
        name = tagnames.get(tag, f"0x{tag:04X}")
        typ_str = TYPE_NAME.get(typ, str(typ))
        if typ == 2:
            val = raw.split(b"\x00")[0].decode("ascii", "replace")
        elif typ in (3, 4, 9) and cnt == 1:
            val = struct.unpack_from(bo + ("H" if typ == 3 else "I"), raw, 0)[0]
        elif typ == 3:
            val = [struct.unpack_from(bo + "H", raw, j)[0] for j in range(0, len(raw), 2)]
        elif typ == 4 or typ == 9:
            val = [struct.unpack_from(bo + "I", raw, j)[0] for j in range(0, len(raw), 4)]
        elif typ == 5:
            val = _fmt_rationals(raw, bo)
        elif typ == 7:
            val = raw.hex()
        else:
            val = raw.hex()
        if tag == 0x0112 and typ == 3:
            orientation = val if isinstance(val, int) else val[0]
        fields.append({"ifd": ifd_name, "tag": name, "tagId": f"0x{tag:04X}",
                       "type": typ_str, "count": cnt, "value": val})

    ifd0_off = struct.unpack_from(bo + "I", tiff, 4)[0]
    ents, nxt = parse_ifd(ifd0_off)
    for tag, typ, cnt, raw in ents:
        emit(IFD0_TAGS, tag, typ, cnt, raw, "IFD0")
    # Exif 子 IFD 与 GPS IFD (递归一层即可, 本素材无更深嵌套)
    for tag, typ, cnt, raw in ents:
        if tag == 0x8769 and typ == 4:
            sub_off = struct.unpack_from(bo + "I", raw, 0)[0]
            sub_ents, _ = parse_ifd(sub_off)
            for st, sty, scnt, sraw in sub_ents:
                emit(EXIF_TAGS, st, sty, scnt, sraw, "ExifIFD")
        if tag == 0x8825 and typ == 4:
            gps_off = struct.unpack_from(bo + "I", raw, 0)[0]
            gps_ents, _ = parse_ifd(gps_off)
            for gt, gty, gcnt, graw in gps_ents:
                emit(GPS_TAGS, gt, gty, gcnt, graw, "GPS")

    jfif_note = {}
    if app0 is not None and len(app0) >= 9 and app0[:5] == b"JFIF\x00":
        units = app0[7]
        xD = struct.unpack_from(">H", app0, 8)[0]
        yD = struct.unpack_from(">H", app0, 10)[0]
        jfif_note = {"version": f"{app0[5]}.{app0[6]:02d}", "units": units,
                     "xDensity": xD, "yDensity": yD}
    return orientation, fields, jfif_note


# ----------------------------------------------------------------------------
# 像素方向变换 (8 种 EXIF Orientation，均经单元测试验证)
# ----------------------------------------------------------------------------
def apply_orientation(px, W, H, orientation):
    """px: RGB 字节串 (长度 W*H*3)；返回 (新字节串, 新W, 新H)。"""
    if orientation == 1:
        return px, W, H

    def dst_xy_from(orientation, x, y, W, H):
        """stored 像素 (x,y) → 输出像素坐标 (xp,yp) 与输出尺寸。"""
        if orientation == 2:      # 水平镜像
            return (W - 1 - x, y), (W, H)
        if orientation == 3:      # 旋转 180
            return (W - 1 - x, H - 1 - y), (W, H)
        if orientation == 4:      # 垂直镜像
            return (x, H - 1 - y), (W, H)
        if orientation == 5:      # 转置 (主对角线镜像)
            return (y, x), (H, W)
        if orientation == 6:      # 旋转 90° 顺时针
            return (H - 1 - y, x), (H, W)
        if orientation == 7:      # 转正交 (副对角线镜像)
            return (H - 1 - y, W - 1 - x), (H, W)
        if orientation == 8:      # 旋转 90° 逆时针
            return (y, W - 1 - x), (H, W)
        raise ValueError(f"非法 Orientation: {orientation}")

    # 先确定输出尺寸 (取一个参考像素)
    _, (out_w, out_h) = dst_xy_from(orientation, 0, 0, W, H)
    out = bytearray(out_w * out_h * 3)
    for y in range(H):
        for x in range(W):
            (xp, yp), _ = dst_xy_from(orientation, x, y, W, H)
            si = (y * W + x) * 3
            di = (yp * out_w + xp) * 3
            out[di:di + 3] = px[si:si + 3]
    return bytes(out), out_w, out_h


# ----------------------------------------------------------------------------
# PPM 读取 与 PNG 写入 (纯标准库)
# ----------------------------------------------------------------------------
def read_ppm(buf):
    i = 0
    n = len(buf)

    def next_token():
        nonlocal i
        while i < n:
            c = buf[i:i + 1]
            if c in (b" ", b"\n", b"\r", b"\t"):
                i += 1
            elif c == b"#":
                while i < n and buf[i:i + 1] != b"\n":
                    i += 1
            else:
                break
        s = i
        while i < n and buf[i:i + 1] not in (b" ", b"\n", b"\r", b"\t"):
            i += 1
        return buf[s:i]

    magic = next_token()
    if magic != b"P6":
        raise ValueError(f"不是 P6 PPM: {magic!r}")
    W = int(next_token())
    H = int(next_token())
    maxv = int(next_token())
    if i < n and buf[i:i + 1] in (b"\n", b"\r", b" ", b"\t"):
        i += 1
    return W, H, buf[i:]


def write_clean_png(path, W, H, rgb):
    def chunk(typ, data):
        return (struct.pack(">I", len(data)) + typ + data
                + struct.pack(">I", zlib.crc32(typ + data) & 0xFFFFFFFF))

    ihdr = struct.pack(">IIBBBBB", W, H, 8, 2, 0, 0, 0)  # 8bit, RGB, no filter
    raw = b"".join(b"\x00" + rgb[y * W * 3:(y + 1) * W * 3] for y in range(H))
    png = (b"\x89PNG\r\n\x1a\n"
           + chunk(b"IHDR", ihdr)
           + chunk(b"IDAT", zlib.compress(raw, 6))
           + chunk(b"IEND", b""))
    with open(path, "wb") as f:
        f.write(png)


def decode_jpeg_pnm(path):
    proc = subprocess.run(
        ["djpeg", "-pnm", path], check=True,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return read_ppm(proc.stdout)


# ----------------------------------------------------------------------------
# 单元测试: 用 2x3 字母网格验证全部 8 种方向 (结果须与教科书一致)
# ----------------------------------------------------------------------------
def selftest():
    g = [["a", "b", "c"], ["d", "e", "f"]]
    W, H = 3, 2
    # 将字母网格编码成 RGB 字节串 (用字母序号作颜色即可，此处仅做坐标映射测试)
    idx = {c: [0, 0, 0] for row in g for c in row}
    for k, c in enumerate(idx):
        idx[c] = bytes([k + 1, 0, 0])
    px = b"".join(b"".join(idx[g[y][x]] for x in range(W)) for y in range(H))

    expected = {
        1: ["a b c", "d e f"],
        2: ["c b a", "f e d"],
        3: ["f e d", "c b a"],
        4: ["d e f", "a b c"],
        5: ["a d", "b e", "c f"],
        6: ["d a", "e b", "f c"],
        7: ["f c", "e b", "d a"],
        8: ["c f", "b e", "a d"],
    }
    reverse = {v[0]: k for k, v in idx.items()}
    ok = True
    for o in range(1, 9):
        out, ow, oh = apply_orientation(px, W, H, o)
        got = []
        for yy in range(oh):
            row = []
            for xx in range(ow):
                b = out[(yy * ow + xx) * 3]
                row.append(reverse.get(b, "?"))
            got.append(" ".join(row))
        status = "PASS" if got == expected[o] else "FAIL"
        if got != expected[o]:
            ok = False
        print(f"  Orientation {o}: {status}")
        if status == "FAIL":
            print(f"    expected={expected[o]!r}\n    got={got!r}")
    print("  selftest:", "ALL PASS" if ok else "HAS FAILURE")
    return ok


# ----------------------------------------------------------------------------
# 主流程
# ----------------------------------------------------------------------------
def main(argv=None):
    ap = argparse.ArgumentParser(description="EXIF 方向应用 + 全量去元数据 → 无损 PNG")
    ap.add_argument("input", nargs="?", default=DEFAULT_INPUT)
    ap.add_argument("output", nargs="?", default=DEFAULT_OUTPUT)
    ap.add_argument("--before", action="store_true", help="仅打印原件 EXIF 字段")
    ap.add_argument("--force", action="store_true", help="允许覆盖已存在的输出文件")
    ap.add_argument("--selftest", action="store_true", help="运行方向变换单元测试")
    args = ap.parse_args(argv)

    if args.selftest:
        sys.exit(0 if selftest() else 1)

    orientation, fields, jfif = parse_exif(args.input)

    if args.before:
        print(f"输入: {args.input}")
        print(f"Orientation = {orientation}")
        print(f"JFIF/APP0 = {json.dumps(jfif, ensure_ascii=False)}")
        for f in fields:
            print(f"  [{f['ifd']}] {f['tag']} ({f['tagId']}, {f['type']}, "
                  f"count={f['count']}) = {f['value']}")
        return 0

    if os.path.exists(args.output) and not args.force:
        print(f"输出已存在，不覆盖: {args.output} (用 --force 覆盖)", file=sys.stderr)
        return 2

    W, H, px = decode_jpeg_pnm(args.input)
    oriented, ow, oh = apply_orientation(px, W, H, orientation)
    write_clean_png(args.output, ow, oh, oriented)

    in_sha = hashlib.sha256(open(args.input, "rb").read()).hexdigest()
    out_sha = hashlib.sha256(open(args.output, "rb").read()).hexdigest()
    print(json.dumps({
        "input": os.path.relpath(args.input, SCRIPT_DIR),
        "input_sha256": in_sha,
        "input_bytes": os.path.getsize(args.input),
        "orientation": orientation,
        "stored_pixels": f"{W}x{H}",
        "output": os.path.relpath(args.output, SCRIPT_DIR),
        "output_sha256": out_sha,
        "output_bytes": os.path.getsize(args.output),
        "output_pixels": f"{ow}x{oh}",
        "metadata": "none (IHDR/IDAT/IEND only)",
    }, ensure_ascii=False, indent=2))
    return 0


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