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24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
import internetarchive
import os
import re
import time


# Change this only if your Archive.org item uses a different identifier.
ITEM_ID = "PSHomeMappedScenes"
ITEM_URL = f"https://archive.org/details/{ITEM_ID}"

# Archive.org creates an item during its first successful file upload. These
# fields are sent only with that one-file creation upload, and only when the
# identifier is still available. They are never resent for an existing item.
ITEM_CREATION_METADATA = {
    "mediatype": "data",
    "collection": "opensource_media",
    "subject": [
        "playstation home",
        "pshome",
        "open source",
        "preservation",
        "revival",
        "archive",
        "scenes",
        "mapped",
        "non-profit",
        "homelab",
        "Home Laboratory",
    ],
}

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
FILE_LIST = os.path.join(SCRIPT_DIR, "log.txt")
SOURCE_DIR = r"Q:\PSHOME-INT\PSHomeCacheDepot\SCENES-MAPPED\ARCHIVE"

# "upload" = upload ZIP files from SOURCE_DIR or from log.txt
# "delete" = delete files listed in log.txt
MODE = "upload"

# True  = send multiple ZIP files in each internetarchive.upload() request.
# False = send one ZIP file per internetarchive.upload() request.
UPLOAD_IN_BATCHES = True

# When UPLOAD_IN_BATCHES is True, this is the number of ZIP files sent in
# each upload request. When it is False, it controls only the optional pause
# interval between groups of individual uploads.
UPLOAD_BATCH_SIZE = 50

# True  = pause after each group of UPLOAD_BATCH_SIZE files.
# False = continue automatically.
PAUSE_AFTER_EACH_UPLOAD_BATCH = False

# False = scan only the ZIP files directly inside SOURCE_DIR.
# True  = upload only the ZIP files listed in log.txt.
UPLOAD_FROM_LOG = False

# In log mode, each entry may be:
#   SceneName$SdatName
#   SceneName$SdatName.zip
#   Q:\PSHOME-INT\PSHomeCacheDepot\SCENES-MAPPED\ARCHIVE\SceneName$SdatName.zip
#
# Scene ZIPs are always uploaded to the root of the Archive.org item. Local
# subfolders and remote subfolder paths are not used.
UPLOAD_LOG_FILE = FILE_LIST

# ZIP files normally do not need Archive.org derivatives.
NO_DERIVE = True

# Leave at 0 so a global queue limit stops cleanly without retrying the same
# ZIP in the same run.
UPLOAD_RETRIES = 0

# Delay after each attempted upload request.
UPLOAD_DELAY_SECONDS = 2.0

# Stop the run when Archive.org reports that its task queue is full.
STOP_ON_RATE_LIMIT = True

UPLOAD_EXTS = {".zip"}
DELETE_EXTS = {".zip", ".torrent"}


def pause_exit():
    input("\nPress Enter to exit...")


def is_allowed_upload_file(name):
    return os.path.splitext(name)[1].lower() in UPLOAD_EXTS


def clean_name(line):
    """Return only the final filename from a name or full path."""
    text = line.strip().strip('"').strip("'").replace("\\", "/")
    return text.rsplit("/", 1)[-1].strip()


def normalize_zip_name(line):
    name = clean_name(line)

    if not name:
        return None

    root, ext = os.path.splitext(name)

    if not root:
        return None

    if not ext:
        return name + ".zip"

    if ext.lower() == ".zip":
        return name

    return None


def normalize_delete_file_name(line):
    name = clean_name(line)

    if not name:
        return None

    root, ext = os.path.splitext(name)

    if not root:
        return None

    if not ext:
        return name + ".zip"

    if ext.lower() in DELETE_EXTS:
        return name

    return None


def normalize_torrent_name(line):
    name = clean_name(line)

    if not name:
        return None

    root, ext = os.path.splitext(name)

    if root and ext.lower() == ".torrent":
        return name

    return None


def remote_name_from_delete_name(name):
    """Scene files live at the Archive.org item root, so no prefix is added."""
    normalized = normalize_delete_file_name(name)

    if not normalized:
        raise ValueError(f"Unsupported delete filename: {name}")

    return normalized


def scan_upload_directory(source_dir):
    """Scan only ZIP files directly inside SOURCE_DIR; never recurse."""
    entries = []
    seen_remote = set()

    with os.scandir(source_dir) as scan:
        files = sorted(
            (entry for entry in scan if entry.is_file()),
            key=lambda entry: entry.name.lower(),
        )

    for entry in files:
        if not is_allowed_upload_file(entry.name):
            continue

        remote_name = entry.name
        remote_low = remote_name.lower()

        if remote_low in seen_remote:
            print(f"[WARN] Duplicate filename skipped: {remote_name}")
            continue

        seen_remote.add(remote_low)
        entries.append((remote_name, entry.path))

    return entries


def normalize_upload_log_entry(line, source_dir):
    raw = line.strip().strip('"').strip("'")

    if not raw:
        return None

    raw = os.path.expandvars(os.path.expanduser(raw))

    if os.path.isabs(raw):
        local_path = os.path.abspath(os.path.normpath(raw))
        source_path = os.path.abspath(os.path.normpath(source_dir))

        if os.path.normcase(os.path.dirname(local_path)) != os.path.normcase(source_path):
            raise ValueError(
                f"Absolute path is not directly inside SOURCE_DIR: {raw}"
            )

        remote_name = os.path.basename(local_path)

    else:
        normalized = raw.replace("\\", "/").strip("/")
        parts = [part for part in normalized.split("/") if part]

        if len(parts) != 1:
            raise ValueError(
                f"Scene upload entries cannot contain subfolders: {raw}"
            )

        remote_name = parts[0]
        local_path = os.path.join(source_dir, remote_name)

    root, ext = os.path.splitext(remote_name)

    if not root:
        raise ValueError(f"Invalid scene ZIP filename: {raw}")

    if not ext:
        remote_name += ".zip"
        local_path += ".zip"
    elif ext.lower() != ".zip":
        raise ValueError(f"Unsupported upload extension: {raw}")

    # Force a root-level remote filename even when an absolute path was used.
    remote_name = clean_name(remote_name)

    return remote_name, os.path.normpath(local_path)


def load_upload_entries_from_log(path, source_dir):
    if not os.path.isfile(path):
        raise FileNotFoundError(f"Missing upload log: {path}")

    entries = []
    seen = set()
    invalid = []

    with open(path, "r", encoding="utf-8-sig", errors="ignore") as file:
        for line_number, line in enumerate(file, start=1):
            if not line.strip():
                continue

            try:
                resolved = normalize_upload_log_entry(line, source_dir)
            except Exception as error:
                message = f"Line {line_number}: {error}"
                print(f"[WARN] {message}")
                invalid.append(message)
                continue

            if not resolved:
                continue

            remote_name, local_path = resolved
            remote_low = remote_name.lower()

            if remote_low in seen:
                print(f"[SKIP LOG DUPLICATE] {remote_name}")
                continue

            seen.add(remote_low)
            entries.append((remote_name, local_path))

    return entries, invalid


def load_file_list(path):
    if not os.path.isfile(path):
        raise FileNotFoundError(f"Missing file: {path}")

    with open(path, "r", encoding="utf-8-sig", errors="ignore") as file:
        raw_lines = [line.strip() for line in file if line.strip()]

    names = []
    seen = set()

    for line in raw_lines:
        name = normalize_delete_file_name(line)

        if not name:
            continue

        name_low = name.lower()

        if name_low not in seen:
            seen.add(name_low)
            names.append(name)

    return names


def list_item_files(item_id):
    item = internetarchive.get_item(item_id)
    names = []

    for remote_file in item.files:
        name = remote_file.get("name")

        if name:
            names.append(name)

    return names


def identifier_is_available(item_id):
    """Return True only when Archive.org says the identifier can be created."""
    item = internetarchive.get_item(item_id)
    return item.identifier_available()


def chunks(items, size):
    for index in range(0, len(items), size):
        yield items[index:index + size]


def is_rate_limit_error(error_text):
    text = str(error_text).lower()
    markers = (
        "please reduce your request rate",
        "total_tasks_queued exceeds global_limit",
        "bucket_tasks_queued exceeds rationed amount",
        "503 slow down",
        "503 slowdown",
    )
    return any(marker in text for marker in markers)


def response_error_text(response):
    parts = []
    status_code = getattr(response, "status_code", None)

    if status_code is not None:
        parts.append(f"HTTP {status_code}")

    reason = getattr(response, "reason", None)

    if reason:
        parts.append(str(reason))

    body = getattr(response, "text", None)

    if body:
        parts.append(str(body))

    return " - ".join(parts)


def upload_file_batch(
    item_id,
    batch_entries,
    batch_number,
    total_batches,
    creation_metadata=None,
):
    """
    Upload one or more files in one internetarchive.upload() request.

    Returns:
        status: "uploaded", "failed", or "rate_limited"
        uploaded_names: files accepted as uploaded
        failed_names: files that could not be submitted/uploaded
        message: error/rate-limit text or None
    """
    valid_entries = []
    failed_names = []

    print("--------------------------------------------------")

    if creation_metadata is not None:
        print(f"[CREATE ITEM] {ITEM_URL}")
        print("[CREATE ITEM] Uploading one ZIP with the initial item metadata.")
    elif UPLOAD_IN_BATCHES:
        print(
            f"[UPLOAD BATCH {batch_number}/{total_batches}] "
            f"{len(batch_entries)} file(s)"
        )
    else:
        print(f"[UPLOAD FILE {batch_number}/{total_batches}]")

    print("--------------------------------------------------")

    for remote_name, local_path in batch_entries:
        if not os.path.isfile(local_path):
            print(f"[ERROR] Missing local file: {local_path}")
            failed_names.append(remote_name)
            continue

        valid_entries.append((remote_name, local_path))

    if not valid_entries:
        return "failed", [], failed_names, "No valid local files in this batch."

    upload_map = {
        remote_name: local_path
        for remote_name, local_path in valid_entries
    }

    if creation_metadata is not None:
        print("[INFO] Sending the one-file item creation request.")
    elif UPLOAD_IN_BATCHES:
        print(
            f"[INFO] Sending {len(upload_map)} file(s) "
            "in one Archive.org upload request."
        )
    else:
        print("[INFO] Sending 1 file in this Archive.org upload request.")

    try:
        upload_options = {
            "verbose": True,
            "queue_derive": not NO_DERIVE,
            "retries": UPLOAD_RETRIES,
        }

        # Do not even pass the metadata argument during ordinary uploads.
        if creation_metadata is not None:
            upload_options["metadata"] = creation_metadata

        result = internetarchive.upload(item_id, upload_map, **upload_options)

        if result is not None:
            try:
                for response in result:
                    status_code = getattr(response, "status_code", None)

                    if status_code is not None and not (200 <= status_code < 300):
                        message = response_error_text(response)

                        if is_rate_limit_error(message):
                            print(f"[RATE LIMIT] {message}")
                            return "rate_limited", [], failed_names, message

                        print(f"[ERROR] Batch upload failed: {message}")
                        failed_names.extend(
                            remote_name
                            for remote_name, local_path in valid_entries
                        )
                        return "failed", [], failed_names, message

            except TypeError:
                # Some internetarchive versions return a non-iterable result.
                pass

        uploaded_names = [
            remote_name
            for remote_name, local_path in valid_entries
        ]

        if creation_metadata is not None:
            print(f"[OK] Created item: {ITEM_URL}")
            print(f"[OK] Uploaded creation ZIP: {uploaded_names[0]}")
        elif UPLOAD_IN_BATCHES:
            print(f"[OK] Uploaded batch: {len(uploaded_names)} file(s)")
        else:
            print(f"[OK] Uploaded: {uploaded_names[0]}")

        return "uploaded", uploaded_names, failed_names, None

    except Exception as error:
        message = str(error)

        if is_rate_limit_error(message):
            print(f"[RATE LIMIT] {message}")
            return "rate_limited", [], failed_names, message

        print(f"[ERROR] Batch upload failed: {message}")
        failed_names.extend(
            remote_name
            for remote_name, local_path in valid_entries
        )
        return "failed", [], failed_names, message

    finally:
        if UPLOAD_DELAY_SECONDS > 0:
            time.sleep(UPLOAD_DELAY_SECONDS)


def upload_entries(item_id, entries, remote_set, creation_metadata=None):
    uploaded = []
    skipped = []
    failed = []
    deferred = []
    entries = list(entries)
    total = len(entries)
    pending_entries = []

    for index, (remote_name, local_path) in enumerate(entries, start=1):
        if remote_name.lower() in remote_set:
            print(f"[SKIP {index}/{total}] Already uploaded: {remote_name}")
            skipped.append(remote_name)
            continue

        pending_entries.append((remote_name, local_path))

    if not pending_entries:
        print("[INFO] No new files remain to upload.")
        return uploaded, skipped, failed, deferred, None

    print()
    print(f"[INFO] New files to upload: {len(pending_entries)}")

    if creation_metadata is not None:
        # Archive.org creates an item through its first file upload. Use exactly
        # one real scene ZIP for that request so creation metadata is sent once.
        creation_entry = pending_entries.pop(0)

        status, creation_uploaded, creation_failed, message = upload_file_batch(
            item_id,
            [creation_entry],
            1,
            1,
            creation_metadata=creation_metadata,
        )

        uploaded.extend(creation_uploaded)
        failed.extend(creation_failed)

        for remote_name in creation_uploaded:
            remote_set.add(remote_name.lower())

        print()

        if status != "uploaded":
            if status == "rate_limited":
                if creation_entry[0].lower() not in remote_set:
                    deferred.append(creation_entry[0])

                stop_reason = "rate_limited"
                print("[INFO] Archive.org's upload/task queue is currently full.")
            else:
                stop_reason = "creation_failed"
                print("[ERROR] The Archive.org item could not be created.")

            for pending_remote, pending_local in pending_entries:
                if pending_remote.lower() not in remote_set:
                    deferred.append(pending_remote)

            print(
                "[INFO] No ordinary uploads were attempted, so the item cannot "
                "be created with incomplete metadata."
            )
            print("[INFO] Correct the error or rerun later; creation will be tried again.")

            if message:
                print(f"[INFO] Creation response: {message}")

            return uploaded, skipped, failed, deferred, stop_reason

        print("[INFO] Initial item metadata has now been sent exactly once.")

        if not pending_entries:
            return uploaded, skipped, failed, deferred, None

    configured_group_size = max(1, UPLOAD_BATCH_SIZE)
    request_size = configured_group_size if UPLOAD_IN_BATCHES else 1
    upload_batches = list(chunks(pending_entries, request_size))
    total_batches = len(upload_batches)

    if UPLOAD_IN_BATCHES:
        print("[INFO] Upload method: multiple files per request")
        print(f"[INFO] Files per upload request: {request_size}")
        print(f"[INFO] Number of upload requests: {total_batches}")
    else:
        print("[INFO] Upload method: one file per request")
        print(f"[INFO] Number of upload requests: {total_batches}")
        print(
            f"[INFO] Optional pause interval: every "
            f"{configured_group_size} individual upload(s)"
        )

    print()

    for batch_index, batch_entries in enumerate(upload_batches, start=1):
        status, batch_uploaded, batch_failed, message = upload_file_batch(
            item_id,
            batch_entries,
            batch_index,
            total_batches,
        )

        uploaded.extend(batch_uploaded)
        failed.extend(batch_failed)

        for remote_name in batch_uploaded:
            remote_set.add(remote_name.lower())

        print()

        if status == "rate_limited":
            for remaining_batch in upload_batches[batch_index - 1:]:
                for pending_remote, pending_local in remaining_batch:
                    if pending_remote.lower() not in remote_set:
                        deferred.append(pending_remote)

            print("[INFO] Archive.org's upload/task queue is currently full.")
            print("[INFO] Stopping instead of attempting the remaining batches.")
            print("[INFO] Rerun later; existing remote files will be skipped.")

            if message:
                print(f"[INFO] Rate-limit message: {message}")

            return uploaded, skipped, failed, deferred, "rate_limited"

        should_pause = False

        if PAUSE_AFTER_EACH_UPLOAD_BATCH and batch_index < total_batches:
            if UPLOAD_IN_BATCHES:
                should_pause = True
            elif batch_index % configured_group_size == 0:
                should_pause = True

        if should_pause:
            if UPLOAD_IN_BATCHES:
                pause_message = (
                    f"[BATCH PAUSE] Finished upload batch "
                    f"{batch_index}/{total_batches} "
                    f"({len(batch_entries)} file(s)). "
                    "Press Enter to continue..."
                )
            else:
                pause_message = (
                    f"[BATCH PAUSE] Finished {batch_index} individual "
                    f"upload(s). Press Enter to continue..."
                )

            input(pause_message)
            print()

    return uploaded, skipped, failed, deferred, None


def find_delete_targets(all_remote_files, file_names):
    remote_set = {name.lower() for name in all_remote_files}
    matches = []
    missing = []
    seen = set()

    for name in file_names:
        try:
            remote_name = remote_name_from_delete_name(name)
        except Exception as error:
            print(f"[WARN] {error}")
            missing.append(name)
            continue

        remote_low = remote_name.lower()

        if remote_low in remote_set:
            if remote_low not in seen:
                seen.add(remote_low)
                matches.append(remote_name)
        else:
            missing.append(remote_name)

    return matches, missing


def delete_remote_files(item_id, remote_names):
    deleted = []
    failed = []

    for name in remote_names:
        print(f"Deleting main file: {name}")

        try:
            internetarchive.delete(
                item_id,
                files=name,
                cascade_delete=False,
                verbose=True,
            )
            print(f"[OK] Deleted: {name}")
            deleted.append(name)
        except Exception as error:
            print(f"[ERROR] Failed deleting {name}: {error}")
            failed.append(name)

        print()

    return deleted, failed


def find_matching_history_backups(all_remote_files, target_names):
    target_set = set()

    for name in target_names:
        try:
            target_set.add(remote_name_from_delete_name(name).lower())
        except Exception:
            pass

    matches = []
    pattern = re.compile(r"^history/files/(.+?)\.~\d+~$", re.IGNORECASE)

    for remote_name in all_remote_files:
        match = pattern.match(remote_name)

        if not match:
            continue

        backed_up_name = match.group(1).replace("\\", "/").lower()

        if backed_up_name in target_set:
            matches.append(remote_name)

    return matches


def delete_backup_files(item_id, backup_names):
    deleted = []
    failed = []

    for remote_name in backup_names:
        print(f"Deleting backup file: {remote_name}")

        try:
            internetarchive.delete(
                item_id,
                files=remote_name,
                cascade_delete=False,
                verbose=True,
            )
            print(f"[OK] Deleted backup: {remote_name}")
            deleted.append(remote_name)
        except Exception as error:
            print(f"[ERROR] Failed deleting backup {remote_name}: {error}")
            failed.append(remote_name)

        print()

    return deleted, failed


def write_log(path, lines):
    with open(path, "w", encoding="utf-8", newline="") as file:
        for line in lines:
            file.write(str(line) + "\n")


def run_upload_mode(item_id, source_dir):
    print("[MODE] UPLOAD")
    print(f"[INFO] Archive.org item: {item_id}")
    print(f"[INFO] Item URL: {ITEM_URL}")
    print(f"[INFO] Source folder: {source_dir}")
    print("[INFO] Directory layout: flat; subfolders are ignored")
    print(f"[INFO] Upload from log: {UPLOAD_FROM_LOG}")

    if UPLOAD_FROM_LOG:
        print(f"[INFO] Upload log: {UPLOAD_LOG_FILE}")

    print(f"[INFO] No derive: {NO_DERIVE}")
    print(f"[INFO] Upload retries: {UPLOAD_RETRIES}")
    print(f"[INFO] Delay after each request: {UPLOAD_DELAY_SECONDS} second(s)")
    print(f"[INFO] Upload in batches: {UPLOAD_IN_BATCHES}")
    print(f"[INFO] Upload group size: {UPLOAD_BATCH_SIZE} file(s)")
    print(f"[INFO] Pause after each upload group: {PAUSE_AFTER_EACH_UPLOAD_BATCH}")
    print()

    if not os.path.isdir(source_dir):
        print(f"[FATAL] Source folder not found: {source_dir}")
        pause_exit()
        return

    if UPLOAD_FROM_LOG:
        try:
            upload_list, invalid_log_entries = load_upload_entries_from_log(
                UPLOAD_LOG_FILE,
                source_dir,
            )
        except Exception as error:
            print(f"[FATAL] Could not load upload log: {error}")
            pause_exit()
            return

        if not upload_list:
            print(f"[WARN] No valid ZIP entries found in: {UPLOAD_LOG_FILE}")

            if invalid_log_entries:
                print(f"[INFO] Invalid log entries: {len(invalid_log_entries)}")

            pause_exit()
            return

        print(f"[OK] Loaded {len(upload_list)} unique ZIP entry/entries from log.txt.")

        if invalid_log_entries:
            print(f"[WARN] Ignored {len(invalid_log_entries)} invalid log entry/entries.")

    else:
        try:
            upload_list = scan_upload_directory(source_dir)
        except Exception as error:
            print(f"[FATAL] Could not scan source folder: {error}")
            pause_exit()
            return

        print(f"[OK] Found {len(upload_list)} root-level ZIP file(s).")

    if not upload_list:
        print("[WARN] No ZIP files were found to upload.")
        pause_exit()
        return

    print()
    print("[INFO] Checking whether the Archive.org identifier already exists...")

    try:
        item_needs_creation = identifier_is_available(item_id)
    except Exception as error:
        print(f"[FATAL] Could not check identifier availability: {error}")
        pause_exit()
        return

    if item_needs_creation:
        creation_metadata = ITEM_CREATION_METADATA
        remote_set = set()
        print(f"[INFO] Identifier is available: {item_id}")
        print("[INFO] The first ZIP will create the item with:")
        print(f"       mediatype: {ITEM_CREATION_METADATA['mediatype']}")
        print(f"       collection: {ITEM_CREATION_METADATA['collection']}")
        print(
            "       subject: "
            + "; ".join(ITEM_CREATION_METADATA["subject"])
        )
    else:
        creation_metadata = None
        print("[OK] Item already exists. Creation metadata will not be resent.")
        print("[INFO] Checking the existing item for uploaded files...")

        try:
            remote_files = list_item_files(item_id)
            remote_set = {name.lower() for name in remote_files}
            print(f"[OK] Remote item has {len(remote_files)} file(s).")
        except Exception as error:
            print(f"[FATAL] Could not list Archive.org item files: {error}")
            pause_exit()
            return

    print()

    uploaded_log = os.path.join(SCRIPT_DIR, "uploaded_ok.txt")
    skipped_log = os.path.join(SCRIPT_DIR, "upload_skipped.txt")
    failed_log = os.path.join(SCRIPT_DIR, "upload_failed.txt")
    deferred_log = os.path.join(SCRIPT_DIR, "upload_deferred.txt")

    uploaded, skipped, failed, deferred, stop_reason = upload_entries(
        item_id,
        upload_list,
        remote_set,
        creation_metadata=creation_metadata,
    )

    write_log(uploaded_log, uploaded)
    write_log(skipped_log, skipped)
    write_log(failed_log, failed)
    write_log(deferred_log, deferred)

    print("========== FINAL SUMMARY ==========")
    print(f"Found:             {len(upload_list)}")
    print(f"Uploaded:          {len(uploaded)}")
    print(f"Skipped existing:  {len(skipped)}")
    print(f"Failed:            {len(failed)}")
    print(f"Deferred:          {len(deferred)}")
    print()
    print(f"Uploaded log: {uploaded_log}")
    print(f"Skipped log:  {skipped_log}")
    print(f"Failed log:   {failed_log}")
    print(f"Deferred log: {deferred_log}")

    if stop_reason == "rate_limited" and STOP_ON_RATE_LIMIT:
        print()
        print("[STOPPED] Archive.org reported that its global task queue is full.")
        print("[INFO] Run the script again later; existing files will be skipped.")

    elif stop_reason == "creation_failed":
        print()
        print("[STOPPED] Item creation failed, so no ordinary uploads were attempted.")
        print("[INFO] Rerun after correcting the reported creation error.")

    if failed:
        print("\nActual failed uploads:")

        for name in failed:
            print(name)


def run_delete_mode(item_id, file_names):
    print("[MODE] DELETE")
    print(f"[INFO] Archive.org item: {item_id}")
    print(f"[OK] Loaded {len(file_names)} supported name(s) from {FILE_LIST}")
    print()
    print("[INFO] Scanning item files...")

    try:
        all_files = list_item_files(item_id)
    except Exception as error:
        print(f"[ERROR] Could not scan item files: {error}")
        pause_exit()
        return

    delete_targets, missing_targets = find_delete_targets(all_files, file_names)
    backup_matches = find_matching_history_backups(all_files, file_names)

    print(f"[INFO] Found {len(delete_targets)} matching main file(s).")
    print(f"[INFO] Missing {len(missing_targets)} requested file(s).")
    print(f"[INFO] Found {len(backup_matches)} matching backup file(s).")
    print()

    delete_target_log = os.path.join(SCRIPT_DIR, "delete_ok.txt")
    missing_target_log = os.path.join(SCRIPT_DIR, "delete_missing.txt")

    write_log(delete_target_log, delete_targets)
    write_log(missing_target_log, missing_targets)

    deleted_main, delete_failed = delete_remote_files(item_id, delete_targets)

    if backup_matches:
        deleted_backups, backup_failed = delete_backup_files(item_id, backup_matches)
    else:
        deleted_backups = []
        backup_failed = []

    print("========== SUMMARY ==========")
    print(f"Files requested:   {len(file_names)}")
    print(f"Main matched:      {len(delete_targets)}")
    print(f"Main missing:      {len(missing_targets)}")
    print(f"Main deleted:      {len(deleted_main)}")
    print(f"Main delete fail:  {len(delete_failed)}")
    print(f"Backups matched:   {len(backup_matches)}")
    print(f"Backups deleted:   {len(deleted_backups)}")
    print(f"Backup del fail:   {len(backup_failed)}")
    print()
    print(f"Resolved delete target log: {delete_target_log}")
    print(f"Missing delete target log:  {missing_target_log}")

    if delete_failed:
        print("\nFailed main deletes:")

        for name in delete_failed:
            print(name)

    if backup_failed:
        print("\nFailed backup deletes:")

        for name in backup_failed:
            print(name)


def main():
    mode = MODE.strip().lower()

    if mode == "upload":
        run_upload_mode(ITEM_ID, SOURCE_DIR)

    elif mode == "delete":
        try:
            file_names = load_file_list(FILE_LIST)
        except Exception as error:
            print(f"[FATAL] {error}")
            pause_exit()
            return

        if not file_names:
            print(f"[WARN] No supported delete entries found in: {FILE_LIST}")
            print(
                "[INFO] Supported entries: .zip, ZIP names without an extension, "
                "and .torrent files."
            )
            pause_exit()
            return

        run_delete_mode(ITEM_ID, file_names)

    else:
        print(f"[FATAL] Invalid MODE: {MODE}")
        print('Use MODE = "upload" or MODE = "delete"')
        pause_exit()
        return

    print("\nDone.")
    pause_exit()


if __name__ == "__main__":
    main()