#!/usr/bin/env python3

import json
import re
import shutil
from pathlib import Path

BASE = Path("/home/bowerybay/public_html")

SOURCE_DIR = BASE / "wilgus-videos-vertical-corrected"
DEST_DIR = BASE / "wilgus-videos-vertical-corrected-address-names"
DATA_FILE = BASE / "wilgus-automation" / "wilgus-property-attributes.json"

ADDRESS_MAX = 25

DEST_DIR.mkdir(parents=True, exist_ok=True)

with DATA_FILE.open("r", encoding="utf-8") as f:
    properties = json.load(f)


def clean_address(address):
    """Convert address to a readable, filename-safe string."""
    address = (address or "").strip()

    # Replace separators/punctuation with spaces.
    address = re.sub(r"[,/\\]+", " ", address)

    # Remove characters unsuitable for filenames.
    address = re.sub(r'[<>:"|?*#]', "", address)

    # Collapse whitespace.
    address = re.sub(r"\s+", " ", address).strip()

    # Limit ADDRESS portion to 25 characters.
    address = address[:ADDRESS_MAX].rstrip(" .-_")

    # Replace spaces with hyphens for easy-to-read filenames.
    address = address.replace(" ", "-")

    return address or "Property"


copied = 0
missing = []
errors = []

for property_id, prop in properties.items():

    property_id = str(property_id)

    source = SOURCE_DIR / f"{property_id}.mp4"

    if not source.exists():
        missing.append(property_id)
        continue

    address = clean_address(prop.get("address"))

    filename = f"{address}-{property_id}.mp4"
    destination = DEST_DIR / filename

    try:
        shutil.copy2(source, destination)
        copied += 1
        print(f"{property_id} -> {filename}")

    except Exception as e:
        errors.append((property_id, str(e)))


print()
print("=" * 50)
print(f"Properties in data: {len(properties)}")
print(f"Videos copied:      {copied}")
print(f"Missing videos:     {len(missing)}")
print(f"Copy errors:        {len(errors)}")
print(f"Destination:        {DEST_DIR}")

if missing:
    print()
    print("Missing property IDs:")
    for property_id in missing:
        print(f"  {property_id}")

if errors:
    print()
    print("Errors:")
    for property_id, error in errors:
        print(f"  {property_id}: {error}")