import os
import json
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  # Change to False when you're confident


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


# filename -> set(user IDs)
file_owners = defaultdict(set)

for entry in attachments:
    filename = entry["filename"]
    user_id = entry["author"]["id"]

    file_owners[filename].add(user_id)


# Find files that have exactly one possible owner
sorted_count = 0
skipped_shared = 0
unknown = 0

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

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

    owners = file_owners.get(filename)

    if not owners:
        print(f"[UNKNOWN] {filename}")
        unknown += 1
        continue

    if len(owners) != 1:
        print(f"[SHARED] {filename} ({len(owners)} owners)")
        skipped_shared += 1
        continue

    user_id = next(iter(owners))

    user_dir = os.path.join(OUTPUT_DIR, user_id)
    destination = os.path.join(user_dir, filename)

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

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

        # Safety check
        if os.path.exists(destination):
            print(f"  [CONFLICT] {destination} already exists, skipping")
            continue

        shutil.move(source, destination)

    sorted_count += 1


print("\nFinished")
print(f"Sorted: {sorted_count}")
print(f"Shared filenames skipped: {skipped_shared}")
print(f"Unknown files: {unknown}")

if DRY_RUN:
    print("DRY_RUN enabled - no files were moved")