# utils/dir_filter.py

import os
import shutil
import cv2
import numpy as np
from PIL import Image
from config import SETTINGS

TARGET_HASH = "0000000000000000"  # эталон
THRESHOLD = 5  # чем выше — тем менее строго сравнение


def average_hash(image, hash_size=8):
    image = image.resize((hash_size, hash_size),
                         Image.Resampling.LANCZOS).convert("L")
    pixels = np.array(image)
    avg = pixels.mean()
    diff = pixels > avg
    bit_string = ''.join('1' if x else '0' for x in diff.flatten())
    return f"{int(bit_string, 2):0{hash_size*hash_size//4}x}"


def hamming_distance(h1, h2):
    return bin(int(h1, 16) ^ int(h2, 16)).count("1")


def first_frame_hash(path):
    cap = cv2.VideoCapture(path)
    ret, frame = cap.read()
    cap.release()
    if not ret:
        return None
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    pil_img = Image.fromarray(frame_rgb)
    return average_hash(pil_img)


def get_video_duration(path):
    cap = cv2.VideoCapture(path)
    if not cap.isOpened():
        return None
    fps = cap.get(cv2.CAP_PROP_FPS)
    frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    cap.release()
    if fps <= 0:
        return None
    return frames / fps  # секунды


def process_folder(folder):
    trash_dir = os.path.join(folder, "_trash")
    short_dir = os.path.join(folder, "_short")

    os.makedirs(trash_dir, exist_ok=True)
    os.makedirs(short_dir, exist_ok=True)

    for file in os.listdir(folder):
        if file.startswith("_trash") or file.startswith("_short"):
            continue

        full_path = os.path.join(folder, file)

        if not os.path.isfile(full_path):
            continue

        if not file.lower().endswith((".mp4", ".mkv", ".avi", ".mov", ".webm")):
            continue

        print(f"\nChecking: {file}")

        # ----------- Проверка длительности ----------- #
        duration = get_video_duration(full_path)
        if duration is None:
            print("  ERROR: cannot read video duration")
        else:
            print(f"  Duration: {duration:.2f}s")
            if duration <= SETTINGS.get("min_video_length", 10):
                print("  SHORT video detected → moving to _short")
                shutil.move(full_path, os.path.join(short_dir, file))
                continue

        # ----------- Проверка по первому кадру ----------- #
        ah = first_frame_hash(full_path)
        if ah is None:
            print("  ERROR: cannot read first frame")
            continue

        dist = hamming_distance(ah, TARGET_HASH)

        if dist <= THRESHOLD:
            print(f"  MATCH (distance={dist}). Moving to _trash.")
            shutil.move(full_path, os.path.join(trash_dir, file))
        else:
            print(f"  OK (distance={dist})")
