File size: 29,914 Bytes
f782430
 
 
4e83ee2
f782430
 
 
 
 
 
 
 
4e83ee2
 
f782430
 
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
 
 
4e83ee2
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
 
 
 
 
 
 
4e83ee2
f782430
 
 
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
 
 
 
 
 
 
 
 
 
 
4e83ee2
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e83ee2
 
f782430
4e83ee2
 
 
 
 
 
 
f782430
4e83ee2
f782430
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
4e83ee2
f782430
 
4e83ee2
f782430
4e83ee2
 
f782430
4e83ee2
 
 
 
f782430
4e83ee2
 
 
 
 
 
 
f782430
 
 
 
4e83ee2
 
 
 
f782430
 
 
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
4e83ee2
f782430
 
4e83ee2
 
 
 
 
 
 
f782430
4e83ee2
 
 
f782430
 
4e83ee2
f782430
4e83ee2
 
 
f782430
4e83ee2
 
 
 
 
 
f782430
4e83ee2
f782430
4e83ee2
 
 
f782430
4e83ee2
 
f782430
 
 
4e83ee2
 
 
 
f782430
4e83ee2
f782430
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
 
4e83ee2
 
f782430
 
 
 
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
 
 
 
 
 
 
 
 
 
4e83ee2
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e83ee2
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
 
4e83ee2
 
f782430
 
 
4e83ee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e83ee2
 
f782430
4e83ee2
 
 
 
f782430
4e83ee2
f782430
4e83ee2
 
 
 
 
 
f782430
 
4e83ee2
 
 
 
f782430
 
 
4e83ee2
 
 
 
 
f782430
 
 
 
4e83ee2
f782430
 
 
 
4e83ee2
 
 
 
 
 
f782430
 
 
 
 
4e83ee2
f782430
 
4e83ee2
 
 
 
 
 
 
 
 
f782430
 
 
 
 
 
 
4e83ee2
f782430
 
 
 
4e83ee2
 
 
 
 
 
 
 
f782430
 
4e83ee2
f782430
 
 
 
 
 
4e83ee2
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e83ee2
 
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e83ee2
 
f782430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
import internetarchive
import os
import re
import time

ITEM_ID = "PSHomeMappedObjects"

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\OBJECTS-MAPPED\ARCHIVE"

# SET THIS:
# "upload" = upload ZIP files using either normal folder scanning or log.txt, selected by UPLOAD_FROM_LOG
# "delete" = delete files listed in log.txt
MODE = "upload"

START_FOLDER = "0"
PAUSE_AFTER_EACH_FOLDER = False

# UPLOAD METHOD SWITCH:
# 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:
#   Number of ZIP files sent in each upload request.
#
# When UPLOAD_IN_BATCHES is False:
#   Files are still uploaded one per request, but this value controls
#   how many individual uploads occur before the optional batch pause.
UPLOAD_BATCH_SIZE = 50

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

# UPLOAD SOURCE SWITCH:
# False = normal mode: scan SOURCE_DIR folders 0-9/A-F starting at START_FOLDER.
# True  = log mode: upload only ZIP files listed in log.txt.
UPLOAD_FROM_LOG = False

# In log mode, entries may be:
#   17031A08-070245ED-A2766E0F-B1ACC605_T032
#   17031A08-070245ED-A2766E0F-B1ACC605_T032.zip
#   1/17031A08-070245ED-A2766E0F-B1ACC605_T032.zip
#   Q:\PSHOME-INT\PSHomeCacheDepot\OBJECTS-MAPPED\ARCHIVE\1\17031A08-070245ED-A2766E0F-B1ACC605_T032.zip
UPLOAD_LOG_FILE = FILE_LIST

# Archive.org upload safety settings.
# ZIP files normally do not need Archive.org derivatives, so leave this True.
NO_DERIVE = True

# Number of automatic retries after a 503 response.
# Leave at 0 so a global queue limit stops cleanly without re-uploading the same ZIP.
UPLOAD_RETRIES = 0

# Delay after each attempted file upload. Increase this if Archive.org throttles often.
UPLOAD_DELAY_SECONDS = 2.0

# Stop the entire run when Archive.org reports its global task queue is full.
# Continuing would only produce thousands of repeated failures.
STOP_ON_RATE_LIMIT = True

FOLDER_ORDER = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
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):
    text = line.strip().strip('"').strip("'").replace("\\", "/")
    return text.split("/")[-1].strip()


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

    if not name:
        return None

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

    if ext == "":
        return name + ".zip"

    if ext_low in DELETE_EXTS:
        return name

    return None


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

    if not name:
        return None

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

    if ext == "":
        return name + ".zip"

    if ext_low == ".zip":
        return name

    return None


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

    if not name:
        return None

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

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

    return None


def normalize_folder(folder):
    return folder.strip().upper()


def get_start_folders():
    start = normalize_folder(START_FOLDER)

    if start not in FOLDER_ORDER:
        raise ValueError(f"Invalid START_FOLDER: {START_FOLDER}")

    start_index = FOLDER_ORDER.index(start)
    return FOLDER_ORDER[start_index:]


def get_folder_from_zip_name(name):
    base = normalize_delete_zip_name(name)

    if not base:
        raise ValueError(f"Invalid zip filename: {name}")

    first = base[:1].upper()

    if first not in FOLDER_ORDER:
        raise ValueError(f"Cannot determine archive folder from filename: {name}")

    return first


def remote_name_from_zip_name(name):
    base = normalize_delete_zip_name(name)

    if not base:
        raise ValueError(f"Invalid zip filename: {name}")

    folder = get_folder_from_zip_name(base)
    return f"{folder}/{base}"


def remote_name_from_torrent_name(name):
    base = normalize_delete_torrent_name(name)

    if not base:
        raise ValueError(f"Invalid torrent filename: {name}")

    return base


def remote_name_from_delete_name(name):
    base = normalize_delete_file_name(name)

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

    ext_low = os.path.splitext(base)[1].lower()

    if ext_low == ".zip":
        return remote_name_from_zip_name(base)

    if ext_low == ".torrent":
        return remote_name_from_torrent_name(base)

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


def remote_name_from_local(source_dir, local_path):
    rel = os.path.relpath(local_path, source_dir)
    return rel.replace("\\", "/")


def scan_upload_folder(source_dir, folder):
    folder_path = os.path.join(source_dir, folder)

    if not os.path.isdir(folder_path):
        print(f"[WARN] Missing local folder: {folder_path}")
        return []

    entries = []
    seen_remote = set()

    for root, dirs, files in os.walk(folder_path):
        dirs.sort()
        files.sort()

        for file_name in files:
            if not is_allowed_upload_file(file_name):
                continue

            local_path = os.path.join(root, file_name)
            remote_name = remote_name_from_local(source_dir, local_path)
            low = remote_name.lower()

            if low in seen_remote:
                print(f"[WARN] Duplicate remote path skipped: {remote_name}")
                continue

            seen_remote.add(low)
            entries.append((remote_name, local_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))
    normalized = raw.replace("\\", "/")

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

        try:
            rel = os.path.relpath(local_path, source_dir)
        except ValueError:
            raise ValueError(f"Path is not on the same drive as SOURCE_DIR: {raw}")

        if rel == os.pardir or rel.startswith(os.pardir + os.sep):
            raise ValueError(f"Absolute path is outside SOURCE_DIR: {raw}")

        remote_name = rel.replace("\\", "/")

    else:
        normalized = normalized.lstrip("/")
        parts = [part for part in normalized.split("/") if part]

        if not parts:
            return None

        if len(parts) == 1:
            file_name = parts[0]
            root, ext = os.path.splitext(file_name)

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

            folder = file_name[:1].upper()

            if folder not in FOLDER_ORDER:
                raise ValueError(f"Cannot determine archive folder from filename: {raw}")

            remote_name = f"{folder}/{file_name}"

        else:
            remote_name = "/".join(parts)
            root, ext = os.path.splitext(remote_name)

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

        local_path = os.path.join(source_dir, *remote_name.split("/"))

    remote_name = remote_name.replace("\\", "/")
    remote_parts = [part for part in remote_name.split("/") if part]

    if len(remote_parts) < 2:
        raise ValueError(f"Upload path must include a 0-9/A-F folder: {raw}")

    top_folder = remote_parts[0].upper()

    if top_folder not in FOLDER_ORDER:
        raise ValueError(f"Invalid top-level archive folder in upload entry: {raw}")

    remote_parts[0] = top_folder
    remote_name = "/".join(remote_parts)

    if os.path.splitext(remote_name)[1].lower() not in UPLOAD_EXTS:
        raise ValueError(f"Unsupported upload extension: {raw}")

    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 f:
        for line_number, line in enumerate(f, start=1):
            if not line.strip():
                continue

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

            if not resolved:
                continue

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

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

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

    return entries, invalid


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

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

    names = []
    seen = set()

    for line in raw:
        name = normalize_delete_file_name(line)

        if not name:
            continue

        low = name.lower()

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

    return names


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

    for f in item.files:
        name = f.get("name")
        if name:
            out.append(name)

    return out


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


def is_rate_limit_error(error_text):
    text = str(error_text).lower()

    rate_limit_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 rate_limit_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):
    """
    Upload multiple 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 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 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:
        result = internetarchive.upload(
            item_id,
            upload_map,
            verbose=True,
            queue_derive=not NO_DERIVE,
            retries=UPLOAD_RETRIES,
        )

        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 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 e:
        message = str(e)

        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):
    uploaded = []
    skipped = []
    failed = []
    deferred = []

    entries = list(entries)
    total = len(entries)

    pending_entries = []

    for index, (remote_name, local_path) in enumerate(entries, start=1):
        remote_low = remote_name.lower()

        if remote_low 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 in this group.")
        return uploaded, skipped, failed, deferred, False

    configured_group_size = max(1, UPLOAD_BATCH_SIZE)

    if UPLOAD_IN_BATCHES:
        request_size = configured_group_size
    else:
        request_size = 1

    upload_batches = list(chunks(pending_entries, request_size))
    total_batches = len(upload_batches)

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

    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":
            deferred = []

            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 now instead of attempting the remaining batches.")
            print("[INFO] Rerun later; files already present remotely will be skipped.")

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

            return uploaded, skipped, failed, deferred, True

        should_pause = False

        if PAUSE_AFTER_EACH_UPLOAD_BATCH and batch_index < total_batches:
            if UPLOAD_IN_BATCHES:
                # Each request is one complete multi-file group.
                should_pause = True
            elif batch_index % configured_group_size == 0:
                # Individual mode: pause only after the configured number
                # of one-file upload requests, not after every single file.
                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, False


def find_delete_targets(all_remote_files, file_names):
    remote_set = {x.lower() for x 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 e:
            print(f"[WARN] {e}")
            missing.append(name)
            continue

        low = remote_name.lower()

        if low in remote_set:
            if low not in seen:
                seen.add(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 e:
            print(f"[ERROR] Failed deleting {name}: {e}")
            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:
        m = pattern.match(remote_name)

        if not m:
            continue

        backed_up_name = m.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 e:
            print(f"[ERROR] Failed deleting backup {remote_name}: {e}")
            failed.append(remote_name)

        print()

    return deleted, failed


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


def run_upload_mode(item_id, source_dir):
    print("[MODE] UPLOAD")
    print(f"[INFO] Source folder: {source_dir}")
    print(f"[INFO] Upload from log: {UPLOAD_FROM_LOG}")

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

    print(f"[INFO] No derive: {NO_DERIVE}")
    print(f"[INFO] Upload retries: {UPLOAD_RETRIES}")
    print(f"[INFO] Delay between attempted uploads: {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:
            log_entries, invalid_log_entries = load_upload_entries_from_log(
                UPLOAD_LOG_FILE,
                source_dir,
            )
        except Exception as e:
            print(f"[FATAL] Could not load upload log: {e}")
            pause_exit()
            return

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

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

            pause_exit()
            return

        upload_groups = [("LOG", log_entries)]

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

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

        print()

    else:
        try:
            folders = get_start_folders()
        except Exception as e:
            print(f"[FATAL] {e}")
            pause_exit()
            return

        upload_groups = []

        for folder in folders:
            entries = scan_upload_folder(source_dir, folder)
            upload_groups.append((folder, entries))

    print("[INFO] Checking archive.org item for existing files...")

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

    print()

    all_uploaded = []
    all_skipped = []
    all_failed = []
    all_deferred = []
    stopped_for_rate_limit = False

    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")

    for group_name, upload_list in upload_groups:
        print("========================================")

        if group_name == "LOG":
            print("[UPLOAD LIST] log.txt")
        else:
            print(f"[FOLDER] {group_name}")

        print("========================================")

        if group_name == "LOG":
            print(f"[OK] Found {len(upload_list)} ZIP file(s) in the upload log.")
        else:
            print(f"[OK] Found {len(upload_list)} ZIP file(s) in folder {group_name}.")

        print()

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

        all_uploaded.extend(uploaded)
        all_skipped.extend(skipped)
        all_failed.extend(failed)
        all_deferred.extend(deferred)

        write_log(uploaded_log, all_uploaded)
        write_log(skipped_log, all_skipped)
        write_log(failed_log, all_failed)
        write_log(deferred_log, all_deferred)

        if group_name == "LOG":
            print("========== LOG UPLOAD SUMMARY ==========")
        else:
            print(f"========== FOLDER {group_name} 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()

        if rate_limited and STOP_ON_RATE_LIMIT:
            stopped_for_rate_limit = True
            break

        if not UPLOAD_FROM_LOG and PAUSE_AFTER_EACH_FOLDER:
            input(
                f"[PAUSE] Finished folder {group_name}. "
                "Press Enter to continue, or close this window to stop..."
            )

        print()

    print("========== FINAL SUMMARY ==========")
    print(f"Uploaded:          {len(all_uploaded)}")
    print(f"Skipped existing:  {len(all_skipped)}")
    print(f"Failed:            {len(all_failed)}")
    print(f"Deferred:          {len(all_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 stopped_for_rate_limit:
        print()
        print("[STOPPED] Archive.org reported that its global task queue is full.")
        print("[INFO] This is a server-side limit, not a damaged ZIP or local network error.")
        print("[INFO] Run the script again later with the same upload source setting.")
        print("[INFO] The script will rescan the item and skip files that are already present.")

    if all_failed:
        print("\nActual failed uploads:")
        for name in all_failed:
            print(name)


def run_delete_mode(item_id, file_names):
    print("[MODE] DELETE")
    print(f"[OK] Loaded {len(file_names)} supported delete file name(s) from {FILE_LIST}")
    print()

    print("[INFO] Scanning item files...")

    try:
        all_files = list_item_files(item_id)
    except Exception as e:
        print(f"[ERROR] Could not scan item files: {e}")
        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 e:
            print(f"[FATAL] {e}")
            pause_exit()
            return

        if not file_names:
            print(f"[WARN] No supported delete entries found in: {FILE_LIST}")
            print("[INFO] Supported delete entries: .zip, no-extension zip names, 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()