#!/usr/bin/env bash
# ==============================================================================
#  DISCODROMO FAMILY DRIVE — GOOGLE PHOTOS IMPORTER (Mac & Linux)
#  Exports & organizes all Google Takeout (.zip) or photo folders into your
#  private 100 GB Discodromo Drive (https://discodromo.party)
# ==============================================================================
set -e

SERVER_URL="https://discodromo.party"
PRE_AUTH_TOKEN=""
PRE_AUTH_DISPLAY=""

echo ""
echo "  ╔══════════════════════════════════════════════════════════════════╗"
echo "  ║  ☁️   DISCODROMO — GOOGLE PHOTOS IMPORTER (100 GB FAMILY VAULT)   ║"
echo "  ╚══════════════════════════════════════════════════════════════════╝"
echo ""

if ! command -v python3 >/dev/null 2>&1; then
  echo "  ❌ Python 3 is required. On macOS, run: xcode-select --install"
  exit 1
fi

export DISCODROMO_URL="$SERVER_URL"
export DISCODROMO_TOKEN="$PRE_AUTH_TOKEN"
export DISCODROMO_USER_DISPLAY="$PRE_AUTH_DISPLAY"
export DISCODROMO_SOURCE_ARG="${1:-}"

python3 - << 'PYEOF' < /dev/tty
import os
import sys
import json
import time
import glob
import zipfile
import hashlib
import re
import getpass
import urllib.request
import urllib.parse
import urllib.error
from datetime import datetime, timezone

SERVER_URL = os.environ.get("DISCODROMO_URL", "https://discodromo.party").rstrip("/")
TOKEN = os.environ.get("DISCODROMO_TOKEN", "").strip()
USER_DISPLAY = os.environ.get("DISCODROMO_USER_DISPLAY", "").strip()
SOURCE_ARG = os.environ.get("DISCODROMO_SOURCE_ARG", "").strip()

MONTH_NAMES = ["", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]

MEDIA_EXTENSIONS = {
    '.jpg', '.jpeg', '.png', '.gif', '.webp', '.heic', '.heif', '.bmp', '.tiff', '.tif',
    '.mp4', '.mov', '.m4v', '.3gp', '.avi', '.mkv', '.webm', '.mts', '.m2ts',
    '.dng', '.raw', '.cr2', '.cr3', '.nef', '.arw', '.orf', '.rw2'
}

IGNORE_FOLDERS = {'trash', 'papelera', 'bin', 'lixeira', 'corbeille', 'papierkorb', '__macosx'}
YEAR_FOLDER_RE = re.compile(
    r'^(?:photos from|fotos de|photos de|foto del|fotos von|untitled|sin t[ií]tulo)?\s*(19\d{2}|20\d{2})$',
    re.IGNORECASE
)
FILENAME_DATE_RE = re.compile(
    r'(?:IMG|VID|PXL|Screenshot|MVIMG|DSC|WA|SIGNAL|PHOTO|VIDEO)?[_\-\s]*(20\d{2}|19\d{2})[\-_]?(0[1-9]|1[0-2])[\-_]?(0[1-9]|[12]\d|3[01])',
    re.IGNORECASE
)

def api_request(method, path, data=None, headers=None, is_json=True):
    url = f"{SERVER_URL}{path}"
    hdrs = {"User-Agent": "Discodromo-GooglePhotos-Importer/1.0"}
    if TOKEN:
        hdrs["X-Family-Token"] = TOKEN
        hdrs["Authorization"] = f"Bearer {TOKEN}"
    if headers:
        hdrs.update(headers)
    body = None
    if data is not None:
        if is_json:
            body = json.dumps(data).encode("utf-8")
            hdrs["Content-Type"] = "application/json"
        else:
            body = data
    req = urllib.request.Request(url, data=body, headers=hdrs, method=method)
    with urllib.request.urlopen(req, timeout=120) as resp:
        raw = resp.read()
        return json.loads(raw.decode("utf-8"))

def format_bytes(n):
    for unit in ["B", "KB", "MB", "GB", "TB"]:
        if n < 1024 or unit == "TB":
            return f"{n:.1f} {unit}" if unit != "B" else f"{int(n)} B"
        n /= 1024.0

# 1. Authenticate
if TOKEN:
    try:
        me = api_request("GET", "/api/auth/me")
        USER_DISPLAY = me["user"]["displayName"]
        used = format_bytes(me["user"]["usedBytes"])
        quota = format_bytes(me["user"]["quotaBytes"])
        print(f"  ✅ Signed in as {USER_DISPLAY} ({used} used of {quota})")
    except Exception:
        TOKEN = ""

if not TOKEN:
    try:
        roster = api_request("GET", "/api/auth/members")
        members = roster.get("members", [])
    except Exception as e:
        print(f"  ❌ Could not reach {SERVER_URL}: {e}")
        sys.exit(1)

    print("  Who is importing Google Photos today?\n")
    for idx, m in enumerate(members, 1):
        print(f"    {idx}) {m['displayName']}")
    print("")

    choice = input("  Select your number (1-8) or type your name: ").strip()
    selected_username = choice
    if choice.isdigit() and 1 <= int(choice) <= len(members):
        selected_username = members[int(choice) - 1]["username"]
        selected_display = members[int(choice) - 1]["displayName"]
    else:
        selected_display = choice

    pw = getpass.getpass(f"  Enter password for {selected_display}: ")
    try:
        res = api_request("POST", "/api/auth/login", {"username": selected_username, "password": pw})
        TOKEN = res["token"]
        USER_DISPLAY = res["user"]["displayName"]
        used = format_bytes(res["user"]["usedBytes"])
        quota = format_bytes(res["user"]["quotaBytes"])
        print(f"\n  ✅ Welcome, {USER_DISPLAY}! ({used} used of {quota} private drive)\n")
    except urllib.error.HTTPError as e:
        print("  ❌ Invalid password. Please try again.")
        sys.exit(1)

# 2. Locate Google Takeout .zip files or photo folders
downloads_dir = os.path.expanduser("~/Downloads")
auto_zips = sorted(
    glob.glob(os.path.join(downloads_dir, "takeout-*.zip")) +
    glob.glob(os.path.join(downloads_dir, "Takeout*.zip"))
)
auto_folders = [
    p for p in (
        os.path.join(downloads_dir, "Takeout"),
        os.path.join(downloads_dir, "Google Photos"),
        os.path.join(downloads_dir, "Google Fotos")
    ) if os.path.isdir(p)
]

sources = []
if SOURCE_ARG and os.path.exists(os.path.expanduser(SOURCE_ARG)):
    sources = [os.path.expanduser(SOURCE_ARG)]
elif auto_zips or auto_folders:
    found_all = auto_zips + auto_folders
    print("  📦 Found Google Takeout exports in your ~/Downloads folder:")
    for f in found_all:
        sz = format_bytes(os.path.getsize(f)) if os.path.isfile(f) else "Folder"
        print(f"     • {os.path.basename(f)} ({sz})")
    print("")
    ans = input("  Press ENTER to import these now, or drag another folder/.zip here: ").strip()
    if not ans:
        sources = found_all
    else:
        clean_ans = ans.strip("'\"").replace("\\ ", " ")
        if os.path.exists(os.path.expanduser(clean_ans)):
            sources = [os.path.expanduser(clean_ans)]
        else:
            print(f"  ❌ Path not found: {clean_ans}")
            sys.exit(1)
else:
    print("  💡 Tip: Download your Google Photos from https://takeout.google.com/settings/takeout/custom/photos")
    ans = input("  Drag & drop your Google Takeout .zip file (or Photos folder) here and press ENTER: ").strip()
    clean_ans = ans.strip("'\"").replace("\\ ", " ")
    if not clean_ans or not os.path.exists(os.path.expanduser(clean_ans)):
        print("  ❌ No valid .zip file or folder provided.")
        sys.exit(1)
    sources = [os.path.expanduser(clean_ans)]

def parse_folder_context(entry_path):
    parts = [p for p in entry_path.replace("\\", "/").split("/") if p and p != "."]
    if len(parts) <= 1:
        return ("timeline", None)
    idx = 0
    if parts[0].lower() == "takeout":
        idx += 1
    if idx < len(parts) - 1 and parts[idx].lower() in ("google photos", "google fotos", "google-fotos"):
        idx += 1
    remaining_dirs = parts[idx:-1]
    for d in remaining_dirs:
        if d.lower() in IGNORE_FOLDERS:
            return ("ignore", None)
    if not remaining_dirs:
        return ("timeline", None)
    top_folder = remaining_dirs[0].strip()
    if YEAR_FOLDER_RE.match(top_folder):
        return ("timeline", None)
    return ("album", top_folder)

def extract_ts_from_meta(meta_obj):
    if not isinstance(meta_obj, dict):
        return None
    for key in ("photoTakenTime", "creationTime"):
        block = meta_obj.get(key)
        if isinstance(block, dict) and block.get("timestamp"):
            try:
                ts = int(block["timestamp"])
                if ts > 0:
                    return ts
            except Exception:
                pass
    return None

def guess_timestamp(filename, folder_name=None, fallback_ts=None):
    m = FILENAME_DATE_RE.search(filename)
    if m:
        try:
            y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
            return int(datetime(y, mo, d, 12, 0, 0, tzinfo=timezone.utc).timestamp())
        except Exception:
            pass
    if folder_name:
        ym = re.search(r'(19\d{2}|20\d{2})', folder_name)
        if ym:
            try:
                return int(datetime(int(ym.group(1)), 6, 15, 12, 0, 0, tzinfo=timezone.utc).timestamp())
            except Exception:
                pass
    if fallback_ts and fallback_ts > 315532800:
        return int(fallback_ts)
    return int(time.time())

def find_matching_meta(entry_path, json_map, json_by_dir):
    for cand in (
        entry_path + ".json",
        entry_path + ".supplemental-metadata.json",
        entry_path + ".supplemental-metada.json",
        entry_path + ".suppl.json",
    ):
        if cand in json_map:
            return json_map[cand]
    base_no_ext, ext = os.path.splitext(entry_path)
    if (base_no_ext + ".json") in json_map:
        return json_map[base_no_ext + ".json"]
    m_num = re.search(r'^(.*)\((\d+)\)$', base_no_ext)
    if m_num:
        for alt in (f"{m_num.group(1)}{ext}({m_num.group(2)}).json", f"{m_num.group(1)}{ext}.json"):
            if alt in json_map:
                return json_map[alt]
    m_ed = re.sub(r'-(?:edited|ha editado|bearbeitet|modifi[eé])$', '', base_no_ext, flags=re.IGNORECASE)
    if m_ed != base_no_ext:
        for cand in (m_ed + ext + ".json", m_ed + ".json"):
            if cand in json_map:
                return json_map[cand]
    dir_name = os.path.dirname(entry_path)
    prefix = os.path.basename(entry_path)[:36].lower()
    for jname, jval in json_by_dir.get(dir_name, []):
        if jname.lower().startswith(prefix):
            return jval
    return None

def upload_media_bytes(raw_bytes, filename, target_folder, taken_ts, sha256_hex):
    size = len(raw_bytes)
    # Direct single-request upload for photos/videos <= 20 MB
    if size <= 20 * 1024 * 1024:
        headers = {
            "Content-Type": "application/octet-stream",
            "X-Target-Folder": urllib.parse.quote(target_folder),
            "X-Filename": urllib.parse.quote(filename),
            "X-Taken-At": str(int(taken_ts)),
            "X-Sha256": sha256_hex
        }
        return api_request("POST", "/api/google-photos/upload-item", data=raw_bytes, headers=headers, is_json=False)
    else:
        # Chunked upload for large videos (8 MB chunks)
        chunk_size = 8 * 1024 * 1024
        total_chunks = max(1, (size + chunk_size - 1) // chunk_size)
        init_res = api_request("POST", "/api/upload/init", {
            "scope": "private",
            "path": target_folder,
            "filename": filename,
            "totalSize": size,
            "totalChunks": total_chunks
        })
        upload_id = init_res["uploadId"]
        for c_idx in range(total_chunks):
            chunk = raw_bytes[c_idx * chunk_size : (c_idx + 1) * chunk_size]
            api_request(
                "POST",
                f"/api/upload/chunk?uploadId={urllib.parse.quote(upload_id)}&chunkIndex={c_idx}",
                data=chunk,
                headers={"Content-Type": "application/octet-stream"},
                is_json=False
            )
        return api_request("POST", "/api/upload/complete", {
            "uploadId": upload_id,
            "takenAt": int(taken_ts),
            "sha256": sha256_hex
        })

total_imported = 0
total_skipped = 0
total_json_cleaned = 0
total_bytes = 0
seen_hashes = set()

for src_path in sources:
    if os.path.isfile(src_path) and src_path.lower().endswith(".zip"):
        print(f"\n  🔍 Scanning archive: {os.path.basename(src_path)} ...")
        json_map = {}
        json_by_dir = {}
        media_items = []

        with zipfile.ZipFile(src_path, "r") as zf:
            for info in zf.infolist():
                if info.is_dir():
                    continue
                norm = info.filename.replace("\\", "/")
                fname = os.path.basename(norm)
                if fname.startswith(".") or "__MACOSX" in norm:
                    continue
                if fname.lower().endswith(".json"):
                    total_json_cleaned += 1
                    if info.file_size < 512 * 1024:
                        try:
                            data = json.loads(zf.read(info).decode("utf-8", errors="replace"))
                            ts = extract_ts_from_meta(data)
                            if ts:
                                json_map[norm] = ts
                                json_by_dir.setdefault(os.path.dirname(norm), []).append((fname, ts))
                        except Exception:
                            pass
                    continue
                _, ext = os.path.splitext(fname.lower())
                if ext not in MEDIA_EXTENSIONS:
                    continue
                kind, album = parse_folder_context(norm)
                if kind == "ignore":
                    continue
                try:
                    zip_ts = int(datetime(*info.date_time, tzinfo=timezone.utc).timestamp())
                except Exception:
                    zip_ts = int(time.time())
                media_items.append((info, norm, fname, kind, album, zip_ts))

            media_items.sort(key=lambda x: (0 if x[3] == "album" else 1, x[1]))
            count = len(media_items)
            print(f"  📸 Found {count} photos & videos (cleaned {total_json_cleaned} .json sidecar files)")

            for idx, (info, norm, fname, kind, album, zip_ts) in enumerate(media_items, 1):
                raw_bytes = zf.read(info)
                sha256_hex = hashlib.sha256(raw_bytes).hexdigest()
                if sha256_hex in seen_hashes:
                    total_skipped += 1
                    print(f"  [{idx}/{count}] ⏭️  Skipped duplicate: {fname}")
                    continue

                taken_ts = find_matching_meta(norm, json_map, json_by_dir) or guess_timestamp(fname, os.path.dirname(norm), zip_ts)
                dt = datetime.fromtimestamp(taken_ts, tz=timezone.utc)
                if kind == "album" and album:
                    safe_album = re.sub(r'[/\\?%*:|"<>]', '_', album).strip() or "Album"
                    target_folder = f"/Fotos/Albums/{safe_album}"
                else:
                    target_folder = f"/Fotos/{dt.year:04d}/{MONTH_NAMES[dt.month]}"

                res = upload_media_bytes(raw_bytes, fname, target_folder, taken_ts, sha256_hex)
                seen_hashes.add(sha256_hex)
                if res.get("skipped"):
                    total_skipped += 1
                    print(f"  [{idx}/{count}] ⏭️  Already in Drive: {target_folder}/{fname}")
                else:
                    total_imported += 1
                    total_bytes += len(raw_bytes)
                    print(f"  [{idx}/{count}] ☁️  Uploaded -> {target_folder}/{fname} ({format_bytes(len(raw_bytes))})")

    elif os.path.isdir(src_path):
        print(f"\n  🔍 Scanning folder: {src_path} ...")
        json_map = {}
        json_by_dir = {}
        media_files = []

        for root, dirs, files in os.walk(src_path):
            for fname in files:
                if fname.startswith("."):
                    continue
                full_p = os.path.join(root, fname)
                rel_p = os.path.relpath(full_p, src_path).replace("\\", "/")
                if fname.lower().endswith(".json"):
                    total_json_cleaned += 1
                    try:
                        with open(full_p, "r", encoding="utf-8", errors="replace") as jf:
                            data = json.load(jf)
                        ts = extract_ts_from_meta(data)
                        if ts:
                            json_map[rel_p] = ts
                            json_by_dir.setdefault(os.path.dirname(rel_p), []).append((fname, ts))
                    except Exception:
                        pass
                    continue
                _, ext = os.path.splitext(fname.lower())
                if ext not in MEDIA_EXTENSIONS:
                    continue
                kind, album = parse_folder_context(rel_p)
                if kind == "ignore":
                    continue
                media_files.append((full_p, rel_p, fname, kind, album))

        media_files.sort(key=lambda x: (0 if x[3] == "album" else 1, x[1]))
        count = len(media_files)
        print(f"  📸 Found {count} photos & videos (ignoring {total_json_cleaned} .json sidecar files)")

        for idx, (full_p, rel_p, fname, kind, album) in enumerate(media_files, 1):
            with open(full_p, "rb") as f:
                raw_bytes = f.read()
            sha256_hex = hashlib.sha256(raw_bytes).hexdigest()
            if sha256_hex in seen_hashes:
                total_skipped += 1
                print(f"  [{idx}/{count}] ⏭️  Skipped duplicate: {fname}")
                continue

            mtime_ts = int(os.path.getmtime(full_p))
            taken_ts = find_matching_meta(rel_p, json_map, json_by_dir) or guess_timestamp(fname, os.path.dirname(rel_p), mtime_ts)
            dt = datetime.fromtimestamp(taken_ts, tz=timezone.utc)
            if kind == "album" and album:
                safe_album = re.sub(r'[/\\?%*:|"<>]', '_', album).strip() or "Album"
                target_folder = f"/Fotos/Albums/{safe_album}"
            else:
                target_folder = f"/Fotos/{dt.year:04d}/{MONTH_NAMES[dt.month]}"

            res = upload_media_bytes(raw_bytes, fname, target_folder, taken_ts, sha256_hex)
            seen_hashes.add(sha256_hex)
            if res.get("skipped"):
                total_skipped += 1
                print(f"  [{idx}/{count}] ⏭️  Already in Drive: {target_folder}/{fname}")
            else:
                total_imported += 1
                total_bytes += len(raw_bytes)
                print(f"  [{idx}/{count}] ☁️  Uploaded -> {target_folder}/{fname} ({format_bytes(len(raw_bytes))})")

print("")
print("  ╔══════════════════════════════════════════════════════════════════╗")
print("  ║  🎉  GOOGLE PHOTOS EXPORT COMPLETE!                              ║")
print("  ╚══════════════════════════════════════════════════════════════════╝")
print(f"  • Family Member : {USER_DISPLAY}")
print(f"  • Photos/Videos : {total_imported} uploaded ({format_bytes(total_bytes)})")
print(f"  • Duplicates    : {total_skipped} skipped")
print(f"  • JSON Clutter  : {total_json_cleaned} sidecar files stripped")
print(f"  • View in Drive : {SERVER_URL} (inside /Fotos)")
print("")
PYEOF
