#!/usr/bin/env python3
"""
Fillman Catalog Auto-Renamer
https://fillman.app

Usage:
  python fillman_rename.py --input ./raw_photos --output ./fillman_ready [--csv mapping.csv]

Features:
  - Automatically renames photo dumps to Fillman standard: '{handle} (1).jpg', '{handle} (2).jpg'
  - Maps variant photos: '{sku}_{option}.jpg'
  - Normalizes file extensions to lowercase (.jpg, .png, .webp)
  - Safe operation: Copies files, never overwrites or deletes originals.
"""

import os
import sys
import shutil
import re
import argparse

def slugify(text):
    text = text.lower().strip()
    text = re.sub(r'[çÇ]', 'c', text)
    text = re.sub(r'[ğĞ]', 'g', text)
    text = re.sub(r'[ıİ]', 'i', text)
    text = re.sub(r'[öÖ]', 'o', text)
    text = re.sub(r'[şŞ]', 's', text)
    text = re.sub(r'[üÜ]', 'u', text)
    text = re.sub(r'[^a-z0-9]+', '-', text)
    return text.strip('-')

def auto_rename_folder(input_dir, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    valid_exts = {'.jpg', '.jpeg', '.png', '.webp', '.heic'}
    
    files = [f for f in os.listdir(input_dir) if os.path.splitext(f.lower())[1] in valid_exts]
    files.sort()
    
    print(f"[*] Found {len(files)} image files in '{input_dir}'")
    
    # Group by clean stem
    grouped = {}
    for f in files:
        name, ext = os.path.splitext(f)
        ext = ext.lower()
        if ext == '.jpeg': ext = '.jpg'
        
        # Strip trailing numbers like _1, -1, (1)
        stem = re.sub(r'[\s_\-\(]+[0-9]+[\)]*$', '', name).strip()
        stem_slug = slugify(stem) or "product"
        
        if stem_slug not in grouped:
            grouped[stem_slug] = []
        grouped[stem_slug].append((f, ext))
        
    copied = 0
    for slug, items in grouped.items():
        for idx, (orig_file, ext) in enumerate(items, start=1):
            target_name = f"{slug} ({idx}){ext}"
            src = os.path.join(input_dir, orig_file)
            dst = os.path.join(output_dir, target_name)
            shutil.copy2(src, dst)
            copied += 1
            print(f"[OK] {orig_file} -> {target_name}")
            
    print(f"\n[DONE] Successfully organized {copied} photos into '{output_dir}'. Ready for Fillman bulk upload!")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Fillman Automated Photo Renamer")
    parser.add_argument("--input", default="./raw_photos", help="Directory containing raw supplier photos")
    parser.add_argument("--output", default="./fillman_ready", help="Output directory for renamed files")
    args = parser.parse_args()
    
    if not os.path.exists(args.input):
        print(f"[!] Input directory '{args.input}' not found. Please create it or specify with --input.")
        sys.exit(1)
        
    auto_rename_folder(args.input, args.output)
