#!/usr/bin/env python3
import csv
import json
from pathlib import Path
from urllib.parse import quote

AUTO_ROOT = Path("/home/bowerybay/public_html/wilgus-automation/properties")
IMAGE_ROOT = Path("/home/bowerybay/public_html/wilgus-images/WILGUS")
OUTFILE = Path("/home/bowerybay/public_html/wilgus-automation/meta-hotel-images.csv")
BASE_URL = "https://bowerybay.com/wilgus-images/WILGUS"

FIELDNAMES = [
    "hotel_id",
    "image[0].url",
    "image[1].url",
    "image[2].url",
    "image[3].url",
    "image[4].url",
    "image[5].url",
]

rows = []
problems = []

for selection_path in sorted(AUTO_ROOT.glob("*/selection.json")):
    prop = selection_path.parent.name

    try:
        record = json.loads(selection_path.read_text())
    except Exception as e:
        problems.append(f"{prop}: cannot read selection.json: {e}")
        continue

    final_files = record.get("final_files", [])
    if len(final_files) != 6:
        problems.append(f"{prop}: expected 6 final_files, found {len(final_files)}")
        continue

    missing = [
        name for name in final_files
        if not (IMAGE_ROOT / prop / name).is_file()
    ]
    if missing:
        problems.append(f"{prop}: missing files: {', '.join(missing)}")
        continue

    row = {"hotel_id": prop}
    for i, name in enumerate(final_files):
        # quote filename safely while preserving normal URL path structure
        row[f"image[{i}].url"] = f"{BASE_URL}/{quote(prop)}/{quote(name)}"
    rows.append(row)

OUTFILE.parent.mkdir(parents=True, exist_ok=True)
with OUTFILE.open("w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=FIELDNAMES)
    writer.writeheader()
    writer.writerows(rows)

print(f"Wrote {len(rows)} properties to:")
print(OUTFILE)

if problems:
    print(f"\nSkipped {len(problems)} properties:")
    for p in problems:
        print(" -", p)
else:
    print("\nAll selection records were valid and all six source images were found.")
