File size: 25,003 Bytes
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
import csv
import os
import glob
import re
from datetime import datetime

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(SCRIPT_DIR)

TARGET_DIR = os.path.join(BASE_DIR, "TABLEDUMPS")
OUTPUT_FILE = os.path.join(BASE_DIR, "uniqueobjects.txt")
FIRST_INTRO_OUTPUT_FILE = os.path.join(BASE_DIR, "uuidfirstintroduced.txt")
DEBUG_UUID_LOG_FILE = os.path.join(BASE_DIR, "debug.log")

DEBUG_UUID_LOG_ENABLED = False

DEBUG_UUIDS = {
    "C080CDE0-DE51455D-BF85BC62-EF65634A",
    "0BB99D3D-11BD4A6C-9F1300E3-3A8E2592",
    "CAFEF00D-BEEFF00D-FEEDBEEF-000010A2",
}

BUILD_MATCHES = {
    "Env_SCEA-Dusty_2": "DEV",
    "Env_HDK_CDEVC-PixelButts": "DEV",
    "Env_HDK-SingstarDev": "DEV",
    "Env_LBP-imagisphere": "DEV",
    "Env_SingStar-SingStarDev": "DEV",
    "Env_SingStar-bowzark": "DEV",
    "Env_SCEASDFPQA-Spouts": "DEV",
    "Env_scea989-Spounts": "DEV",
    "Env_KungFuFactorydba-PixelButts": "DEV",
    "Env_homecoretest-Soul 1": "DEV",
    "Env_veemeescee-QuantumDoja2": "DEV",
    "Env_veemeetovss-Soul 4 DECH2500": "DEV",
    "cqa-a-Soul 3": "DEV",
    "cqa-a-Viciousest": "DEV",
    "cpreprod-QuantumDoja1": "DEV",
    "cqa-e-QuantumDoja": "DEV",
    "cqa-e-Soul 3": "DEV",
    "ObjectCatalogue_5_SCEA_2012-11-12": "BETA",
    "ObjectCatalogue_5_SCEE_2012-11-12": "BETA",
}

OUTPUT_FIELDS = [
    "UUID_TXXX",
    "ObjectId",
    "Version",
    "Build",
]

FIRST_INTRO_BASE_OUTPUT_FIELDS = [
    "UUID",
    "First Date Introduced",
    "Last Date Removed",
]

READDED_FIELD_NAME = "Removed Date->Added Back Date"


def get_build_from_file_path(file_path):
    path_text = file_path.replace("\\", "/").lower()

    for text, build in BUILD_MATCHES.items():
        if text.lower() in path_text:
            return build

    return "RETAIL"


def version_num(value):
    try:
        return int(str(value).strip())
    except:
        return -1


def build_rank(build):
    if build == "RETAIL":
        return 0
    if build == "BETA":
        return 1
    return 2


def should_replace_existing(old_row, new_row):
    old_rank = build_rank(old_row["Build"])
    new_rank = build_rank(new_row["Build"])

    if new_rank < old_rank:
        return True

    if new_rank > old_rank:
        return False

    return version_num(new_row["Version"]) > version_num(old_row["Version"])


def clean_fieldnames(fieldnames):
    return [
        h.strip().replace("\ufeff", "")
        for h in fieldnames
    ]


def parse_catalogue_date_from_filename(file_path):
    filename = os.path.basename(file_path)

    m = re.match(
        r"^ObjectCatalogue_5_[^_]+_(\d{4}-\d{2}-\d{2})(?:_|-|\.|$)",
        filename,
        re.IGNORECASE
    )

    if m:
        return datetime.strptime(m.group(1), "%Y-%m-%d").date()

    m = re.match(
        r"^OBJECTCATALOGUE_(\d{4}-\d{2}-\d{2})(?:_|-|\.|$)",
        filename,
        re.IGNORECASE
    )

    if m:
        return datetime.strptime(m.group(1), "%Y-%m-%d").date()

    return None


def format_date(date_value):
    if not date_value:
        return ""

    return date_value.strftime("%Y-%m-%d")


def find_first_intro_csv_files():
    patterns = [
        os.path.join(TARGET_DIR, "**", "*_Combined.csv"),
        os.path.join(TARGET_DIR, "**", "ObjectCatalogue_5_*_Objects.csv"),
    ]

    found = []

    for pattern in patterns:
        found.extend(glob.glob(pattern, recursive=True))

    seen = set()
    result = []

    for path in found:
        key = os.path.abspath(path).lower()
        if key not in seen:
            seen.add(key)
            result.append(path)

    return result


def get_object_ids_from_csv(csv_file):
    object_ids = set()

    rows_read = 0
    rows_skipped_missing_objectid = 0

    with open(csv_file, "r", encoding="utf-8-sig", errors="replace", newline="") as f:
        reader = csv.DictReader(f, delimiter=",")

        if not reader.fieldnames:
            return object_ids, rows_read, rows_skipped_missing_objectid, "no header found"

        fieldnames_clean = clean_fieldnames(reader.fieldnames)
        reader.fieldnames = fieldnames_clean

        if "ObjectId" in fieldnames_clean:
            object_id_field = "ObjectId"
        elif len(fieldnames_clean) >= 2:
            object_id_field = fieldnames_clean[1]
            print(f"  WARNING: ObjectId header not found. Using COL B: {repr(object_id_field)}")
        else:
            return object_ids, rows_read, rows_skipped_missing_objectid, "ObjectId missing and COL B does not exist"

        for row in reader:
            rows_read += 1

            uuid = row.get(object_id_field, "").strip()

            if not uuid:
                rows_skipped_missing_objectid += 1
                continue

            object_ids.add(uuid.upper())

    return object_ids, rows_read, rows_skipped_missing_objectid, None


def debug_write(debug_file, message):
    if not DEBUG_UUID_LOG_ENABLED:
        return

    if debug_file is None:
        return

    debug_file.write(message + "\n")
    debug_file.flush()


def debug_uuid_event(debug_file, uuid, message):
    if uuid.upper() not in DEBUG_UUIDS:
        return

    debug_write(debug_file, f"{uuid.upper()}\t{message}")


def debug_snapshot_status(debug_file, current_date, current_uuids, previous_uuids, removed_now, added_now, currently_removed):
    if not DEBUG_UUID_LOG_ENABLED:
        return

    for debug_uuid in sorted(DEBUG_UUIDS):
        status = "PRESENT" if debug_uuid in current_uuids else "MISSING"

        if debug_uuid in added_now:
            change = "ADDED_SINCE_PREVIOUS"
        elif debug_uuid in removed_now:
            change = "REMOVED_SINCE_PREVIOUS"
        elif debug_uuid in previous_uuids and debug_uuid in current_uuids:
            change = "STILL_PRESENT"
        elif debug_uuid not in previous_uuids and debug_uuid not in current_uuids:
            change = "STILL_MISSING"
        else:
            change = "NO_CHANGE"

        removed_state = ""

        if debug_uuid in currently_removed:
            removed_state = f"CURRENTLY_REMOVED_SINCE={format_date(currently_removed[debug_uuid])}"

        debug_write(
            debug_file,
            f"{debug_uuid}\tDATE={format_date(current_date)}\tSTATUS={status}\tCHANGE={change}\t{removed_state}"
        )


def build_first_intro_log():
    if os.path.exists(FIRST_INTRO_OUTPUT_FILE):
        print("------------------------------------------------------------")
        print("First-introduced output file already exists. Skipping uuidfirstintroduced.txt only.")
        print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}")
        print("------------------------------------------------------------")
        return

    debug_file = None

    if DEBUG_UUID_LOG_ENABLED:
        debug_file = open(DEBUG_UUID_LOG_FILE, "w", encoding="utf-8", newline="")
        debug_write(debug_file, "UUID\tDebug")
        debug_write(debug_file, "------------------------------------------------------------")
        debug_write(debug_file, "Starting UUID debug trace")
        debug_write(debug_file, f"Target dir: {TARGET_DIR}")
        debug_write(debug_file, f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}")
        debug_write(debug_file, "Debug UUIDs:")

        for debug_uuid in sorted(DEBUG_UUIDS):
            debug_write(debug_file, f"{debug_uuid}\tWATCHING")

        debug_write(debug_file, "------------------------------------------------------------")

    try:
        first_intro_files = find_first_intro_csv_files()

        date_to_uuids = {}
        date_to_files = {}

        files_read = 0
        files_skipped_dev_beta = 0
        files_skipped_no_date = 0
        files_skipped_missing_objectid = 0
        rows_read = 0
        rows_skipped_missing_objectid = 0

        print()
        print("------------------------------------------------------------")
        print("Building first-introduced / last-removed UUID date log...")
        print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}")

        if DEBUG_UUID_LOG_ENABLED:
            print(f"Debug UUID log file: {DEBUG_UUID_LOG_FILE}")

        print(f"Found {len(first_intro_files)} candidate file(s).")
        print("------------------------------------------------------------")
        print()

        for csv_file in first_intro_files:
            build = get_build_from_file_path(csv_file)

            if build != "RETAIL":
                files_skipped_dev_beta += 1
                debug_write(debug_file, f"SKIP_FILE_DEV_BETA\t{csv_file}\tBuild={build}")
                continue

            catalogue_date = parse_catalogue_date_from_filename(csv_file)

            if catalogue_date is None:
                files_skipped_no_date += 1
                debug_write(debug_file, f"SKIP_FILE_NO_DATE\t{csv_file}")
                continue

            print("------------------------------------------------------------")
            print(f"Reading snapshot file: {csv_file}")
            print(f"Date: {format_date(catalogue_date)}")
            print(f"Build: {build}")

            debug_write(
                debug_file,
                f"READ_FILE\tDate={format_date(catalogue_date)}\tBuild={build}\t{csv_file}"
            )

            try:
                object_ids, file_rows_read, file_rows_skipped, error = get_object_ids_from_csv(csv_file)

                rows_read += file_rows_read
                rows_skipped_missing_objectid += file_rows_skipped

                if error:
                    print(f"  SKIP: {error}")
                    files_skipped_missing_objectid += 1
                    debug_write(
                        debug_file,
                        f"SKIP_FILE_OBJECTID_ERROR\tDate={format_date(catalogue_date)}\tError={error}\t{csv_file}"
                    )
                    continue

                if catalogue_date not in date_to_uuids:
                    date_to_uuids[catalogue_date] = set()
                    date_to_files[catalogue_date] = []

                date_to_uuids[catalogue_date].update(object_ids)
                date_to_files[catalogue_date].append(csv_file)

                files_read += 1

                print(f"  Rows read: {file_rows_read}")
                print(f"  Skipped missing ObjectId: {file_rows_skipped}")
                print(f"  UUIDs found in file: {len(object_ids)}")

                for debug_uuid in sorted(DEBUG_UUIDS):
                    if debug_uuid in object_ids:
                        debug_write(
                            debug_file,
                            f"{debug_uuid}\tFOUND_IN_FILE\tDate={format_date(catalogue_date)}\t{csv_file}"
                        )
                    else:
                        debug_write(
                            debug_file,
                            f"{debug_uuid}\tNOT_FOUND_IN_FILE\tDate={format_date(catalogue_date)}\t{csv_file}"
                        )

            except Exception as e:
                print(f"  ERROR reading file: {e}")
                debug_write(
                    debug_file,
                    f"ERROR_READING_FILE\tDate={format_date(catalogue_date)}\tError={e}\t{csv_file}"
                )
                continue

        sorted_dates = sorted(date_to_uuids.keys())

        first_intro = {}
        last_removed = {}
        currently_removed = {}
        readded_events_by_uuid = {}

        previous_date = None
        previous_uuids = set()
        ever_seen = set()

        debug_write(debug_file, "------------------------------------------------------------")
        debug_write(debug_file, "Processing snapshots in date order")

        for current_date in sorted_dates:
            current_uuids = date_to_uuids[current_date]

            print("------------------------------------------------------------")
            print(f"Processing snapshot date: {format_date(current_date)}")
            print(f"Files combined for this date: {len(date_to_files[current_date])}")
            print(f"UUIDs in snapshot: {len(current_uuids)}")

            debug_write(
                debug_file,
                f"SNAPSHOT\tDate={format_date(current_date)}\tFiles={len(date_to_files[current_date])}\tUUIDs={len(current_uuids)}"
            )

            for path in date_to_files[current_date]:
                debug_write(debug_file, f"SNAPSHOT_FILE\tDate={format_date(current_date)}\t{path}")

            # First snapshot only establishes the starting set.
            if previous_date is None:
                for uuid in current_uuids:
                    first_intro[uuid] = current_date
                    ever_seen.add(uuid)

                    if uuid in DEBUG_UUIDS:
                        debug_uuid_event(
                            debug_file,
                            uuid,
                            f"FIRST_SNAPSHOT_PRESENT\tFirst Date Introduced={format_date(current_date)}"
                        )

                for debug_uuid in sorted(DEBUG_UUIDS):
                    if debug_uuid not in current_uuids:
                        debug_uuid_event(
                            debug_file,
                            debug_uuid,
                            f"FIRST_SNAPSHOT_MISSING\tDate={format_date(current_date)}"
                        )

                previous_date = current_date
                previous_uuids = current_uuids
                continue

            removed_now = previous_uuids - current_uuids
            added_now = current_uuids - previous_uuids

            debug_snapshot_status(
                debug_file,
                current_date,
                current_uuids,
                previous_uuids,
                removed_now,
                added_now,
                currently_removed
            )

            for uuid in added_now:
                if uuid not in ever_seen:
                    first_intro[uuid] = current_date
                    ever_seen.add(uuid)

                    debug_uuid_event(
                        debug_file,
                        uuid,
                        f"FIRST_INTRODUCED\tDate={format_date(current_date)}"
                    )

                if uuid in currently_removed:
                    removed_date = currently_removed[uuid]
                    event_text = f"{format_date(removed_date)}->{format_date(current_date)}"

                    if uuid not in readded_events_by_uuid:
                        readded_events_by_uuid[uuid] = []

                    readded_events_by_uuid[uuid].append(event_text)

                    debug_uuid_event(
                        debug_file,
                        uuid,
                        f"REMOVED_THEN_ADDED_BACK\t{event_text}"
                    )

                    del currently_removed[uuid]

            for uuid in removed_now:
                last_removed[uuid] = previous_date
                currently_removed[uuid] = previous_date

                debug_uuid_event(
                    debug_file,
                    uuid,
                    f"REMOVED\tLast Date Removed={format_date(previous_date)}\tMissing On={format_date(current_date)}"
                )

            for debug_uuid in sorted(DEBUG_UUIDS):
                if debug_uuid in current_uuids and debug_uuid not in added_now:
                    debug_uuid_event(
                        debug_file,
                        debug_uuid,
                        f"PRESENT_AFTER_DATE_COMPARE\tDate={format_date(current_date)}"
                    )

                if debug_uuid not in current_uuids and debug_uuid not in removed_now:
                    debug_uuid_event(
                        debug_file,
                        debug_uuid,
                        f"MISSING_AFTER_DATE_COMPARE\tDate={format_date(current_date)}"
                    )

            print(f"  Added since previous snapshot: {len(added_now)}")
            print(f"  Removed since previous snapshot: {len(removed_now)}")

            previous_date = current_date
            previous_uuids = current_uuids

        final_rows = []

        for uuid in sorted(first_intro.keys()):
            final_rows.append({
                "UUID": uuid,
                "First Date Introduced": format_date(first_intro[uuid]),
                "Last Date Removed": format_date(last_removed.get(uuid)),
                "Readded Events": readded_events_by_uuid.get(uuid, []),
            })

        max_readded_event_count = 0

        for row in final_rows:
            count = len(row["Readded Events"])
            if count > max_readded_event_count:
                max_readded_event_count = count

        first_intro_output_fields = (
            FIRST_INTRO_BASE_OUTPUT_FIELDS +
            ([READDED_FIELD_NAME] * max_readded_event_count)
        )

        with open(FIRST_INTRO_OUTPUT_FILE, "w", encoding="utf-8", newline="") as f:
            writer = csv.writer(f, delimiter="\t")
            writer.writerow(first_intro_output_fields)

            for row in final_rows:
                output_row = [
                    row["UUID"],
                    row["First Date Introduced"],
                    row["Last Date Removed"],
                ]

                readded_events = row["Readded Events"]

                for event_text in readded_events:
                    output_row.append(event_text)

                while len(output_row) < len(first_intro_output_fields):
                    output_row.append("")

                writer.writerow(output_row)

        debug_write(debug_file, "------------------------------------------------------------")
        debug_write(debug_file, "Finished UUID debug trace")
        debug_write(debug_file, f"Snapshot dates processed: {len(sorted_dates)}")

        total_readded_events = 0
        for events in readded_events_by_uuid.values():
            total_readded_events += len(events)

        debug_write(debug_file, f"Removed-then-added events written into uuidfirstintroduced.txt: {total_readded_events}")

        for debug_uuid in sorted(DEBUG_UUIDS):
            debug_write(debug_file, "------------------------------------------------------------")
            debug_write(debug_file, f"{debug_uuid}\tFINAL")
            debug_write(debug_file, f"{debug_uuid}\tFirst Date Introduced={format_date(first_intro.get(debug_uuid))}")
            debug_write(debug_file, f"{debug_uuid}\tLast Date Removed={format_date(last_removed.get(debug_uuid))}")

            events = readded_events_by_uuid.get(debug_uuid, [])

            if events:
                for event_text in events:
                    debug_write(debug_file, f"{debug_uuid}\tRemoved Date->Added Back Date={event_text}")
            else:
                debug_write(debug_file, f"{debug_uuid}\tRemoved Date->Added Back Date=")

        print("------------------------------------------------------------")
        print("First-introduced / last-removed log done.")
        print(f"Candidate files found: {len(first_intro_files)}")
        print(f"Files read: {files_read}")
        print(f"Files skipped DEV/BETA: {files_skipped_dev_beta}")
        print(f"Files skipped missing date in filename: {files_skipped_no_date}")
        print(f"Files skipped missing ObjectId/COL B: {files_skipped_missing_objectid}")
        print(f"Snapshot dates processed: {len(sorted_dates)}")
        print(f"Rows read total: {rows_read}")
        print(f"Skipped missing ObjectId: {rows_skipped_missing_objectid}")
        print(f"Unique UUID rows written: {len(final_rows)}")
        print(f"Removed-then-added events written into uuidfirstintroduced.txt: {total_readded_events}")
        print(f"Extra Removed Date->Added Back Date field count: {max_readded_event_count}")
        print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}")

        if DEBUG_UUID_LOG_ENABLED:
            print(f"Debug UUID log file: {DEBUG_UUID_LOG_FILE}")

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

    finally:
        if debug_file is not None:
            debug_file.close()


def main():
    if not os.path.isdir(TARGET_DIR):
        print("ERROR: Target directory does not exist.")
        print(f"Target directory: {TARGET_DIR}")
        input("")
        return

    if os.path.exists(OUTPUT_FILE):
        print("------------------------------------------------------------")
        print("Main output file already exists. Skipping uniqueobjects.txt only.")
        print(f"Output file: {OUTPUT_FILE}")
        print("Second log will still be checked.")
        print("------------------------------------------------------------")

        build_first_intro_log()

        input("")
        return

    csv_files = glob.glob(
        os.path.join(TARGET_DIR, "**", "*_Combined.csv"),
        recursive=True
    )

    if not csv_files:
        print("ERROR: No *_Combined.csv files found.")
        print(f"Searched in: {TARGET_DIR}")
        print("Second log will still be checked.")
        build_first_intro_log()
        input("")
        return

    print(f"Script dir: {SCRIPT_DIR}")
    print(f"Base dir: {BASE_DIR}")
    print(f"Target dir: {TARGET_DIR}")
    print(f"Output file: {OUTPUT_FILE}")
    print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}")

    if DEBUG_UUID_LOG_ENABLED:
        print(f"Debug UUID log file: {DEBUG_UUID_LOG_FILE}")

    print()
    print(f"Found {len(csv_files)} *_Combined.csv file(s).")
    print()

    unique = {}

    total_rows_read = 0
    total_skipped_missing_uuid = 0
    total_skipped_missing_fields = 0

    for csv_file in csv_files:
        build = get_build_from_file_path(csv_file)

        print("------------------------------------------------------------")
        print(f"Processing: {csv_file}")
        print(f"Build: {build}")

        rows_in_file = 0
        skipped_in_file = 0

        try:
            with open(csv_file, "r", encoding="utf-8-sig", errors="replace", newline="") as f:
                reader = csv.DictReader(f, delimiter=",")

                if not reader.fieldnames:
                    print("  SKIP: no header found")
                    total_skipped_missing_fields += 1
                    continue

                fieldnames_clean = clean_fieldnames(reader.fieldnames)
                reader.fieldnames = fieldnames_clean

                required = ["UUID_TXXX", "ObjectId", "Version"]
                missing = [field for field in required if field not in fieldnames_clean]

                if missing:
                    print(f"  SKIP: missing field(s): {', '.join(missing)}")
                    print("  Headers found:")

                    for h in fieldnames_clean:
                        print(f"    {repr(h)}")

                    total_skipped_missing_fields += 1
                    continue

                for row in reader:
                    total_rows_read += 1
                    rows_in_file += 1

                    uuid = row.get("UUID_TXXX", "").strip()

                    if not uuid:
                        total_skipped_missing_uuid += 1
                        skipped_in_file += 1
                        continue

                    cleaned = {
                        "UUID_TXXX": uuid,
                        "ObjectId": row.get("ObjectId", "").strip(),
                        "Version": row.get("Version", "").strip(),
                        "Build": build,
                    }

                    if uuid not in unique:
                        unique[uuid] = cleaned
                    else:
                        if should_replace_existing(unique[uuid], cleaned):
                            unique[uuid] = cleaned

        except Exception as e:
            print(f"  ERROR reading file: {e}")
            continue

        print(f"  Rows read: {rows_in_file}")
        print(f"  Skipped missing UUID_TXXX: {skipped_in_file}")

    final_rows = list(unique.values())

    final_rows.sort(
        key=lambda r: (
            r["ObjectId"].upper(),
            -version_num(r["Version"]),
        )
    )

    with open(OUTPUT_FILE, "w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=OUTPUT_FIELDS, delimiter="\t")
        writer.writeheader()
        writer.writerows(final_rows)

    build_first_intro_log()

    print("------------------------------------------------------------")
    print("Done.")
    print(f"CSV files found: {len(csv_files)}")
    print(f"Rows read total: {total_rows_read}")
    print(f"Skipped missing UUID_TXXX: {total_skipped_missing_uuid}")
    print(f"Skipped files missing fields/header: {total_skipped_missing_fields}")
    print(f"Unique UUID_TXXX rows written: {len(final_rows)}")
    print(f"Output file: {OUTPUT_FILE}")
    print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}")

    if DEBUG_UUID_LOG_ENABLED:
        print(f"Debug UUID log file: {DEBUG_UUID_LOG_FILE}")

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

    input("")


if __name__ == "__main__":
    main()