# -*- coding: utf-8 -*-
import os
from collections import Counter
from config import CONTENT_LABELS, SUPPORTED_FORMATS, LANG
from utils import (
    get_image_time, get_image_location, get_image_content_label,
    deduplicate_photos, rename_photo,
    is_organized, save_organized_record
)

def organize_photos(folder_path, lang="zh"):
    all_photos = []
    for f in os.listdir(folder_path):
        full = os.path.join(folder_path, f)
        if f.lower().endswith(SUPPORTED_FORMATS) and not is_organized(full):
            all_photos.append(full)

    total_count = len(all_photos)
    if total_count == 0:
        return {"code": 200, "msg": LANG[lang]["processed"].format(0), "data": []}

    unique_photos = deduplicate_photos(all_photos)
    duplicate_count = total_count - len(unique_photos)

    result = []
    label_counts = Counter()

    for p in unique_photos:
        t = get_image_time(p)
        l = get_image_location(p)
        c = get_image_content_label(p, CONTENT_LABELS)
        label_counts[c] += 1

        parts = [t, c, l]
        parts = [x for x in parts if x.strip()]
        new_name = "_".join(parts)
        ok, new_p = rename_photo(p, new_name)

        if ok:
            save_organized_record(p)
            save_organized_record(new_p)

        result.append({
            "old": p, "new": new_name, "label": c, "status": "OK" if ok else "FAIL"
        })

    msg = [
        LANG[lang]["total"].format(total_count),
        LANG[lang]["duplicate"].format(duplicate_count),
        LANG[lang]["remaining"].format(len(unique_photos)),
        LANG[lang]["processed"].format(len(unique_photos)),
        LANG[lang]["label_stat"],
    ]
    for lbl, cnt in label_counts.most_common():
        msg.append(f"  {lbl}: {cnt}")

    return {
        "code": 200,
        "total": total_count,
        "duplicate": duplicate_count,
        "remaining": len(unique_photos),
        "label_counts": dict(label_counts),
        "message": "\n".join(msg),
        "data": result
    }

if __name__ == "__main__":
    res = organize_photos("./test_photos", lang="zh")
    print(res["message"])