import json
import os
import shutil
from collections import defaultdict

FILES_DIR = "/home/mariserve/discord/filesbot/files/0"
OUTPUT_DIR = "/home/mariserve/discord/filesbot/files"
JSON_FILE = "attachments.json"

DRY_RUN = False

VOSTRO_OWNER = "1159974001821630518"

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

# filename -> possible owners
owners = defaultdict(set)

# Unique attachment groups (messages)
messages = []

seen_messages = set()

for entry in attachments:
    filename = entry["filename"]
    owner = entry["owner"]["id"]

    owners[filename].add(owner)

    files = tuple(sorted(entry["message_files"]))

    if files not in seen_messages:
        seen_messages.add(files)
        messages.append(files)

print(f"{len(messages)} attachment groups loaded.")

# ----------------------------------------------------
# Hardcoded ownership rules
# ----------------------------------------------------

for filename in os.listdir(FILES_DIR):
    if filename.startswith("vostro_"):
        owners[filename] = {VOSTRO_OWNER}

# ----------------------------------------------------
# Propagate ownership through attachment groups
# ----------------------------------------------------

passes = 0

while True:
    changed = False
    passes += 1

    for files in messages:
        known_users = set()
        unknown_files = []

        for filename in files:
            if len(owners[filename]) == 1:
                known_users |= owners[filename]
            else:
                unknown_files.append(filename)

        if len(known_users) != 1:
            continue

        if not unknown_files:
            continue

        user = next(iter(known_users))

        for filename in unknown_files:
            if owners[filename] != {user}:
                owners[filename] = {user}
                changed = True

    if not changed:
        break

print(f"Propagation finished after {passes} passes.")

# ----------------------------------------------------
# Move files
# ----------------------------------------------------

sorted_count = 0
shared_count = 0
unknown_count = 0

for filename in os.listdir(FILES_DIR):
    source = os.path.join(FILES_DIR, filename)

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

    # Hardcoded rule always wins
    if filename.startswith("vostro_"):
        owner = VOSTRO_OWNER

    elif filename not in owners:
        print(f"[UNKNOWN] {filename}")
        unknown_count += 1
        continue

    elif len(owners[filename]) != 1:
        print(f"[SHARED] {filename} -> {owners[filename]}")
        shared_count += 1
        continue

    else:
        owner = next(iter(owners[filename]))

    destination_dir = os.path.join(OUTPUT_DIR, owner)
    destination = os.path.join(destination_dir, filename)

    print(f"[MOVE] {filename} -> {owner}")

    if not DRY_RUN:
        os.makedirs(destination_dir, exist_ok=True)

        if os.path.exists(destination):
            print("    Destination already exists, skipping.")
            continue

        shutil.move(source, destination)

    sorted_count += 1

print()
print("Finished")
print(f"Sorted: {sorted_count}")
print(f"Shared filenames skipped: {shared_count}")
print(f"Unknown files: {unknown_count}")

if DRY_RUN:
    print("\nDRY_RUN is enabled. No files were moved.")