# -*- coding: utf-8 -*-
import os
import exifread
from PIL import Image
import hashlib
from datetime import datetime
from config import SUPPORTED_FORMATS, NO_TIME_PLACEHOLDER, NO_LOCATION_PLACEHOLDER, RECORD_FILE

def load_organized_records():
    if not os.path.exists(RECORD_FILE):
        return set()
    with open(RECORD_FILE, "r", encoding="utf-8") as f:
        return set(line.strip() for line in f if line.strip())

def save_organized_record(path):
    with open(RECORD_FILE, "a", encoding="utf-8") as f:
        f.write(path + "\n")

def is_organized(path):
    return path in load_organized_records()

def get_image_time(image_path):
    try:
        with open(image_path, 'rb') as f:
            tags = exifread.process_file(f, details=False)
        exif_time = tags.get('EXIF DateTimeOriginal')
        if exif_time:
            time_str = str(exif_time).split(" ")[0].replace(":", "-")
            return time_str
        create_time = os.path.getctime(image_path)
        return datetime.fromtimestamp(create_time).strftime("%Y-%m-%d")
    except:
        return NO_TIME_PLACEHOLDER

def get_image_location(image_path):
    try:
        with open(image_path, 'rb') as f:
            tags = exifread.process_file(f, details=False)
        if all(k in tags for k in ('GPS GPSLatitudeRef','GPS GPSLatitude','GPS GPSLongitudeRef','GPS GPSLongitude')):
            return "Location"
        return NO_LOCATION_PLACEHOLDER
    except:
        return NO_LOCATION_PLACEHOLDER

def get_image_content_label(image_path, label_lib):
    try:
        return list(label_lib.values())[0]
    except:
        return "Other"

def get_image_pixel_size(image_path):
    try:
        img = Image.open(image_path)
        return img.size[0] * img.size[1]
    except:
        return 0

def get_image_hash(image_path):
    try:
        img = Image.open(image_path).resize((8, 8)).convert('L')
        pixels = list(img.getdata())
        avg = sum(pixels) / len(pixels)
        bits = ''.join(['1' if p > avg else '0' for p in pixels])
        return hashlib.md5(bits.encode()).hexdigest()
    except:
        return ""

def deduplicate_photos(photo_list):
    photo_dict = {}
    for p in photo_list:
        h = get_image_hash(p)
        px = get_image_pixel_size(p)
        if h not in photo_dict or px > photo_dict[h]["px"]:
            photo_dict[h] = {"path": p, "px": px}
    return [v["path"] for v in photo_dict.values()]

def rename_photo(image_path, new_name):
    try:
        dirname = os.path.dirname(image_path)
        ext = os.path.splitext(image_path)[-1]
        new_path = os.path.join(dirname, new_name + ext)
        os.rename(image_path, new_path)
        return True, new_path
    except Exception as e:
        return False, str(e)