#!/usr/bin/env python3
"""Extract dark-pixel fraction and horizontal centroid from local images.
Original course teaching example. SPDX-License-Identifier: MIT.
"""
import argparse
import hashlib
from pathlib import Path
import platform
from common import output_dir, read_csv, write_csv, write_json


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("manifest", help="CSV: path,label,session,split; optional source")
    parser.add_argument("--out", required=True)
    parser.add_argument("--threshold", type=int, default=100)
    parser.add_argument("--bottom-fraction", type=float, default=0.5)
    args = parser.parse_args()
    try:
        from PIL import Image, ImageOps, __version__ as pillow_version
        if not 0 <= args.threshold <= 255 or not 0 < args.bottom_fraction <= 1:
            raise ValueError("Require threshold 0..255 and 0 < bottom-fraction <= 1")
        manifest = Path(args.manifest).resolve()
        rows = read_csv(manifest, ["path", "label", "session", "split"])
        features = []
        for index, row in enumerate(rows, start=2):
            if row["label"] not in ("left", "center", "right") or row["split"] not in ("train", "test"):
                raise ValueError(f"row {index}: label must be left/center/right; split train/test")
            if not (row["session"] or "").strip() or not row["path"]:
                raise ValueError(f"row {index}: session and path must be filled")
            path = (manifest.parent / row["path"]).resolve()
            with Image.open(path) as original:
                gray = ImageOps.exif_transpose(original).convert("L")
                width, height = gray.size
                if width < 2 or height < 2:
                    raise ValueError(f"Image too small: {path}")
                top = min(height - 1, int(height * (1 - args.bottom_fraction)))
                pixels = gray.crop((0, top, width, height)).getdata()
                dark_count = x_sum = 0
                for i, value in enumerate(pixels):
                    if value < args.threshold:
                        dark_count += 1
                        x_sum += i % width
            features.append({
                "path": str(path), "label": row["label"], "session": row["session"].strip(),
                "split": row["split"], "source": row.get("source") or "user_provided",
                "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
                "width": width, "height": height, "roi_top": top,
                "threshold": args.threshold, "bottom_fraction": args.bottom_fraction,
                "has_dark": int(dark_count > 0),
                "dark_fraction": dark_count / (width * (height - top)),
                "centroid_x": x_sum / dark_count / (width - 1) if dark_count else ""})
        out = output_dir(args.out)
        write_csv(out / "features.csv", list(features[0]), features)
        write_json(out / "vision-summary.json", {
            "manifest": str(manifest), "images": len(features),
            "without_dark_pixels": sum(row["has_dark"] == 0 for row in features),
            "threshold": args.threshold, "bottom_fraction": args.bottom_fraction,
            "python": platform.python_version(), "pillow": pillow_version,
            "notes": ["Dark means grayscale value < threshold in the bottom ROI.",
                      "centroid_x is normalized 0..1 across image width. No dark pixels => empty centroid, has_dark=0.",
                      "Labels and session groups come from the manifest, never from the extracted centroid. Use independent human labels for real images.",
                      "These are laptop features, not onboard camera inference or measured robot steering."]})
        print(f"Extracted {len(features)} images to {out}")
    except ImportError:
        parser.error("Install Pillow in your environment: python -m pip install Pillow")
    except (OSError, ValueError) as exc:
        parser.error(str(exc))


if __name__ == "__main__":
    main()
