File size: 24,117 Bytes
034f112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92fb6e4
034f112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92fb6e4
 
 
 
 
 
 
 
034f112
 
92fb6e4
 
 
 
 
 
034f112
 
 
92fb6e4
 
 
 
 
 
 
 
 
 
034f112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92fb6e4
034f112
92fb6e4
 
 
 
034f112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92fb6e4
 
 
 
 
034f112
 
 
 
 
92fb6e4
 
034f112
92fb6e4
 
 
034f112
92fb6e4
 
 
 
 
 
 
065c61a
034f112
 
92fb6e4
 
 
 
 
 
034f112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd62084
 
 
 
 
92fb6e4
 
 
 
 
 
 
034f112
 
 
 
 
 
 
 
 
 
 
 
92fb6e4
 
 
 
 
 
034f112
92fb6e4
 
 
 
 
 
 
 
 
034f112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Phase 2 — Semantic Normalization / Identity Extraction
Compliments Reference DB Pipeline

Input: Phase 1 output (phase1_output.parquet)
Output: Phase 2 output (phase2_output.parquet)

This phase performs:
  1. Brand normalization → brand_norm + product_line (uses brand_clean from Phase 1)
  2. Identity attribute extraction from ORIGINAL title (BEFORE normalization)
  3. Fat-level and fat-percentage extraction
  4. Flavour extraction
  5. Formulation extraction
  6. Variant/size attribute parsing
  7. Core-title extraction (strip brand prefix + size)

CRITICAL: Identity information is extracted from the ORIGINAL title
before any destructive normalization removes it.

Phase 1 (data quality) has already cleaned:
  - brand → brand_clean (whitespace/case normalization)
  - title → title_clean (whitespace normalization)
  - upc → upc_raw (preserved, not altered)
  - external_id → external_id_raw (preserved, not altered)

Phase 2 uses brand_clean for semantic normalization, and original title
for identity extraction.
"""

import json
import re
import sys
from datetime import datetime, timezone
from pathlib import Path

import pandas as pd
import numpy as np

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
BASE_DIR = Path(__file__).resolve().parent.parent
INPUT_PATH = BASE_DIR.parent / "phase1" / "outputs" / "phase1_output.parquet"
OUTPUT_DIR = BASE_DIR / "outputs"
VALIDATION_DIR = BASE_DIR / "validation"
STATISTICS_DIR = BASE_DIR / "statistics"

VERSION = "3.0.0"
TIMESTAMP = datetime.now(timezone.utc).isoformat()


def log(msg: str) -> None:
    print(f"[Phase2] {msg}")


# ---------------------------------------------------------------------------
# 1. Brand Normalization
# ---------------------------------------------------------------------------
# Maps 11 raw brand variants → (brand_norm, product_line)
# Case-insensitive matching

BRAND_MAP = {
    "compliments organic":       ("Compliments", "Organic"),
    "compliments balance":       ("Compliments", "Balance"),
    "compliments naturally simple": ("Compliments", "Naturally Simple"),
    "compliments green care":    ("Compliments", "Green"),
    "compliments green":         ("Compliments", "Green"),
    "compliments little ones":   ("Compliments", "Little Ones"),
    "sensations":                ("Sensations", "Sensations"),
    "compliments":               ("Compliments", "Core"),
    "compliments ":              ("Compliments", "Core"),   # trailing space
    " compliments":              ("Compliments", "Core"),   # leading space
}


def normalize_brand(clean_brand: str) -> tuple[str, str]:
    """Map cleaned brand string to (brand_norm, product_line).
    
    Phase 1 has already cleaned the brand field (whitespace trim, case normalization).
    This function performs SEMANTIC normalization: mapping brand variants to canonical
    brand + product_line.
    """
    if pd.isna(clean_brand):
        return ("Unknown", "Core")
    key = str(clean_brand).strip().lower()
    if key in BRAND_MAP:
        return BRAND_MAP[key]
    # Default: if it contains "compliments", treat as Core Compliments
    if "compliments" in key:
        return ("Compliments", "Core")
    if "sensations" in key:
        return ("Sensations", "Sensations")
    return (str(clean_brand).strip(), "Core")


# ---------------------------------------------------------------------------
# 2. Identity Attribute Extraction
# ---------------------------------------------------------------------------
# Extracted from the ORIGINAL title BEFORE any normalization

def extract_identity_flags(title: str) -> dict:
    """Extract 9 boolean identity flags from raw product title."""
    t = title.lower()
    return {
        "is_organic": bool(re.search(r"\borganic\b", t)),
        "is_gluten_free": bool(re.search(r"\bgluten[\s-]+free\b", t)),
        "is_naturally_simple": bool(re.search(r"\bnaturally\s+simple\b", t)),
        "is_sugar_free": bool(re.search(
            r"\bsugar[\s-]+free\b|\b(?:no sugar added|unsweetened)\b|\bzero\s+sugar\b", t)),
        "is_unsalted": bool(re.search(r"\bunsalted\b|\bno salt\b", t)),
        "is_lactose_free": bool(re.search(r"\blactose[\s-]+free\b", t)),
        "is_peanut_free": bool(re.search(r"\bpeanut[\s-]+free\b", t)),
        "is_plant_based": bool(re.search(r"\bplant[\s-]*based\b", t)),
        "is_reduced_sodium": bool(re.search(
            r"\breduced\s+sodium\b|\blow\s+sodium\b|\bno\s+salt\s+added\b", t)),
    }


# ---------------------------------------------------------------------------
# 3. Fat Level and Fat Percentage Extraction
# ---------------------------------------------------------------------------

def extract_fat_info(title: str) -> dict:
    """Extract fat_level and fat_percentage from raw product title."""
    t = title.lower()

    # Fat level
    fat_level = "regular"
    if re.search(r"\b(?:light|lite|reduced fat|low fat|lean)\b", t):
        fat_level = "reduced_fat"
    elif re.search(r"\bfat[\s-]+free\b", t):
        fat_level = "fat_free"

    # Fat percentage — extract numeric % from title
    fat_percentage = None
    pct_match = re.search(r"(\d+(?:\.\d+)?)\s*%", title)
    if pct_match:
        val = float(pct_match.group(1))
        # Skip values that are clearly not fat percentages
        # (cocoa %, alcohol %, etc.)
        skip_context = any(w in t for w in ["cocoa", "alcohol", "isopropyl", "peanuts"])
        if val < 100 and not skip_context:
            fat_percentage = val
            # Override fat_level if percentage is very low
            if 0 < val <= 0.7:
                fat_level = "fat_free"

    return {
        "fat_level": fat_level,
        "fat_percentage": fat_percentage,
    }


# ---------------------------------------------------------------------------
# 4. Flavour Extraction
# ---------------------------------------------------------------------------

FLAVOUR_KEYWORDS = [
    "almond", "apple", "banana", "blueberry", "caramel", "cherry",
    "chocolate", "cinnamon", "coconut", "cranberry", "honey", "lemon",
    "lime", "mango", "maple", "mixed berry", "peach", "peanut",
    "peppermint", "pineapple", "pomegranate", "raspberry", "strawberry",
    "tropical", "vanilla", "watermelon", "white chocolate", "berry",
    "espresso", "caramel", "butterscotch", "toffee",
]

# Plural patterns for keywords where simple "s?" is insufficient
_FLAVOUR_PLURAL_PATTERNS = {
    "berry": r"berr(?:y|ies)",
    "cherry": r"cherr(?:y|ies)",
    "peach": r"peach(?:es)?",
    "mango": r"mang(?:o|os)",
}


def extract_flavours(title: str) -> list[str]:
    """Extract flavour keywords from raw product title.

    Uses word-boundary regex to prevent false positives from substring
    matching (e.g., 'lime' inside 'compliments', 'apple' inside 'pineapple').
    Multi-word keywords use substring match (they are distinctive enough).
    """
    t = title.lower()
    found = []
    for kw in FLAVOUR_KEYWORDS:
        if ' ' in kw:
            if kw in t:
                found.append(kw)
        else:
            if kw in _FLAVOUR_PLURAL_PATTERNS:
                pat = _FLAVOUR_PLURAL_PATTERNS[kw]
            else:
                pat = re.escape(kw) + r"s?"
            if re.search(r'\b' + pat + r'\b', t):
                found.append(kw)
    return sorted(set(found))


# ---------------------------------------------------------------------------
# 5. Formulation Extraction
# ---------------------------------------------------------------------------

FORMULATION_KEYWORDS = [
    "smooth", "crunchy", "creamy", "chunky", "whole", "halves",
    "sliced", "ground", "chopped", "breaded", "fresh", "frozen",
    "roasted", "smoked",
]


def extract_formulation(title: str) -> list[str]:
    """Extract formulation keywords from raw product title."""
    t = title.lower()
    found = []
    for kw in FORMULATION_KEYWORDS:
        if kw in t:
            found.append(kw)
    return sorted(set(found))


# ---------------------------------------------------------------------------
# 6. Variant Attributes Parsing
# ---------------------------------------------------------------------------

def build_variant_attributes(size_str: str) -> dict:
    """Parse raw size string into structured variant attributes."""
    if not size_str or pd.isna(size_str):
        return {}

    s = str(size_str).strip()
    attrs = {}

    # Try to match: [qty x ] amount unit [x multiplier]
    m = re.match(
        r"(\d+(?:\.\d+)?)\s*x\s*"  # qty x
        r"(\d+(?:\.\d+)?)\s*"       # amount
        r"(g|kg|ml|l|oz|lb)s?\s*$",  # unit
        s, re.IGNORECASE
    )
    if m:
        attrs["qty"] = int(float(m.group(1)))
        attrs["amount"] = float(m.group(2))
        attrs["unit"] = m.group(3).lower()
        return attrs

    # Try: amount unit [x multiplier]
    m = re.match(
        r"(\d+(?:\.\d+)?)\s*"        # amount
        r"(g|kg|ml|l|oz|lb)s?\s*"     # unit
        r"(?:x\s*(\d+))?\s*$",        # optional x multiplier
        s, re.IGNORECASE
    )
    if m:
        attrs["amount"] = float(m.group(1))
        attrs["unit"] = m.group(2).lower()
        if m.group(3):
            attrs["multiplier"] = int(m.group(3))
        return attrs

    # Try: count-based (e.g. "12 per pack", "20 count", "100 tablets")
    m = re.match(
        r"(\d+)\s*(?:per\s+pack|count|ea|pack|piece|slice|cups?|pound|"
        r"tablets?|caplets?|capsules?|sachets?|sticks?|bars?|rolls?|sheets?|"
        r"bags?|bulbs?|lamps?|lozenges?|plugs?|pairs?|liners?|wipes?|strips?|"
        r"sprays?|cots?|napkins?|boxes?|pods?)s?\s*$",
        s, re.IGNORECASE
    )
    if m:
        attrs["count"] = int(m.group(1))
        return attrs

    # Fallback: store raw string
    attrs["raw"] = s
    return attrs


# ---------------------------------------------------------------------------
# 7. Core Title Extraction
# ---------------------------------------------------------------------------

# Brand/product-line prefixes to strip from title
BRAND_PREFIXES = [
    ("Compliments Naturally Simple ", ""),
    ("Compliments Balance ", ""),
    ("Compliments Organic ", ""),
    ("Compliments Green Care ", ""),
    ("Compliments Little Ones ", ""),
    ("Compliments ", ""),
    ("Sensations ", ""),
]

# Trailing size/weight/count patterns to strip
# Applied iteratively to handle multiple trailing patterns
# More specific patterns first, then general patterns
SIZE_PATTERNS = [
    # Multi-pack patterns: "12 x 355 ml", "6 x 170 g", "12 x 100 Feet"
    r"\s+\d+\s*x\s+\d+\s*(?:g|kg|ml|l|oz|lb|feet|yards?)s?\s*$",
    r"\s+\d+\s*x\s+\d+\s*(?:tablets?|caplets?|capsules?|sheets?|bags?|rolls?)\s*$",
    r"\s+\d+\s*x\s*$",
    # Dimension patterns: "12 Inch x 100 Feet", "8-Inch", "9-Inch"
    r"\s+\d+(?:\.\d+)?[\s-]*inch(?:es)?\s*x\s*\d+\s*(?:feet|yards?)s?\s*$",
    r"\s+\d+(?:\.\d+)?[\s-]*inch(?:es)?\s*$",
    # Count-based patterns
    r"\s+\d+\s*(?:tablets?|caplets?|capsules?|sachets?|sticks?|bars?|rolls?|sheets?|bags?|bulbs?|lamps?|lozenges?|plugs?|pairs?|liners?|wipes?|strips?|sprays?|cots?|napkins?|boxes?|pods?)\s*$",
    r"\s+\d+\s*(?:tea\s+)?bags?\s*$",
    r"\s+\d+\s*(?:tea\s+)?sachets?\s*$",
    r"\s+\d+\s*(?:count|ea|pack|pieces?|slice|cups?)\s*$",
    r"\s+\d+\s+per\s+pack\s*$",
    r"\s+\d+\s+count\s*$",
    # Weight/volume patterns
    r"\s+\d[\d,.]*\s*(?:g|kg|ml|l|oz|lb|litre|liters?|pound)s?\s*$",
    # Length patterns: "100 Feet", "4.5 Yards"
    r"\s+\d[\d,.]*\s*(?:feet|yards?)s?\s*$",
    # Ounce patterns for cups/plates: "12 oz", "16-ounce"
    r"\s+\d+(?:\.\d+)?[\s-]*(?:oz|ounce)s?\s*$",
]

# Bracket content to strip
BRACKET_PATTERN = r"\s*\([^)]*\)\s*"


def extract_core_title(title: str, product_line: str) -> str:
    """Extract core product title by stripping brand prefix and size info."""
    t = title.strip()

    # Step 1: Strip brand/product-line prefix
    for prefix, replacement in BRAND_PREFIXES:
        if t.lower().startswith(prefix.lower()):
            t = replacement + t[len(prefix):]
            break

    # Step 2: Strip bracket content (must happen BEFORE SIZE_PATTERNS
    # so that trailing "(can)", "(bottle)" etc. don't block size stripping)
    t = re.sub(BRACKET_PATTERN, " ", t)

    # Step 3: Strip trailing size/weight/count patterns
    # Apply iteratively to handle multiple trailing patterns
    # e.g., "Aluminum Foil 12 Inch x 100 Feet" -> "Aluminum Foil"
    prev = None
    while prev != t:
        prev = t
        for pat in SIZE_PATTERNS:
            t = re.sub(pat, "", t, flags=re.IGNORECASE)

    # Step 4: Clean up whitespace
    t = re.sub(r"\s+", " ", t).strip()

    return t


# ---------------------------------------------------------------------------
# 8. Identity Hash (for reference — grouping happens in Phase 3)
# ---------------------------------------------------------------------------

def build_identity_hash(row: dict) -> str:
    """Build deterministic identity hash from extracted attributes.
    
    Version 3.0.0: Includes normalized_core_title to prevent over-grouping.
    Products with different core_titles get different hashes.
    Size/package differences are variant attributes, not identity.
    """
    parts = []
    
    # Product identity (normalized core title ensures different products don't merge)
    core_title = row.get("core_title", "")
    # Normalize core title for grouping: lowercase, remove special chars, sort words
    norm_core = re.sub(r"[^a-z0-9\s]", " ", core_title.lower())
    norm_core = " ".join(sorted(norm_core.split()))
    parts.append(norm_core)
    
    # Identity flags
    for col in ["is_organic", "is_gluten_free", "is_naturally_simple",
                 "is_sugar_free", "is_unsalted", "is_lactose_free",
                 "is_peanut_free", "is_plant_based", "is_reduced_sodium"]:
        parts.append("1" if row.get(col) else "0")

    fp = row.get("fat_percentage")
    if pd.notna(fp) and fp is not None:
        parts.append(f"fat{fp:.2g}" if fp else "fat0")
    else:
        parts.append("fat_none")

    parts.append(str(row.get("fat_level", "regular")))
    parts.append(str(row.get("product_line", "Core")))

    fl = row.get("flavour", [])
    parts.append(",".join(sorted(fl)) if fl else "")

    fm = row.get("formulation", [])
    parts.append(",".join(sorted(fm)) if fm else "")

    return "|".join(parts)


# ---------------------------------------------------------------------------
# Main Processing
# ---------------------------------------------------------------------------

def process_phase2(df: pd.DataFrame) -> pd.DataFrame:
    """Apply all Phase 2 transformations."""
    log(f"Processing {len(df)} products ...")

    # CRITICAL: Extract identity from ORIGINAL title BEFORE any normalization
    log("Step 1: Extracting identity flags from original titles ...")
    identity_flags = df["title"].apply(extract_identity_flags)
    id_df = pd.DataFrame(identity_flags.tolist())
    for col in id_df.columns:
        df[col] = id_df[col].values

    log("Step 2: Extracting fat info ...")
    fat_info = df["title"].apply(extract_fat_info)
    fat_df = pd.DataFrame(fat_info.tolist())
    df["fat_level"] = fat_df["fat_level"].values
    df["fat_percentage"] = fat_df["fat_percentage"].values

    log("Step 3: Extracting flavours ...")
    df["flavour"] = df["title"].apply(extract_flavours)

    log("Step 4: Extracting formulations ...")
    df["formulation"] = df["title"].apply(extract_formulation)

    log("Step 5: Normalizing brands (using brand_clean from Phase 1) ...")
    brand_col = "brand_clean" if "brand_clean" in df.columns else "brand"
    brand_results = df[brand_col].apply(normalize_brand)
    df["brand_norm"] = brand_results.apply(lambda x: x[0])
    df["product_line"] = brand_results.apply(lambda x: x[1])

    log("Step 6: Parsing variant attributes ...")
    df["variant_attributes"] = df["size"].apply(
        lambda x: json.dumps(build_variant_attributes(x)) if pd.notna(x) else "{}"
    )

    log("Step 7: Extracting core titles ...")
    df["core_title"] = df.apply(
        lambda row: extract_core_title(row["title"], row["product_line"]),
        axis=1
    )

    log("Step 8: Building identity hash ...")
    df["identity_hash"] = df.apply(lambda row: build_identity_hash(row.to_dict()), axis=1)

    log(f"Processing complete. Output shape: {df.shape}")
    return df


# ---------------------------------------------------------------------------
# Validation
# ---------------------------------------------------------------------------

def validate_phase2(df_in: pd.DataFrame, df_out: pd.DataFrame) -> dict:
    """Validate Phase 2 output."""
    checks = {}

    # Row count preserved
    checks["row_count"] = {
        "input": len(df_in),
        "output": len(df_out),
        "pass": len(df_in) == len(df_out),
    }

    # All original columns preserved
    original_cols = set(df_in.columns)
    output_cols = set(df_out.columns)
    missing_original = original_cols - output_cols
    checks["original_columns_preserved"] = {
        "missing": list(missing_original),
        "pass": len(missing_original) == 0,
    }

    # New columns added
    new_cols = output_cols - original_cols
    expected_new = {
        "brand_norm", "product_line",
        "is_organic", "is_gluten_free", "is_naturally_simple",
        "is_sugar_free", "is_unsalted", "is_lactose_free",
        "is_peanut_free", "is_plant_based", "is_reduced_sodium",
        "fat_level", "fat_percentage",
        "flavour", "formulation",
        "variant_attributes",
        "core_title", "identity_hash",
    }
    missing_new = expected_new - new_cols
    checks["new_columns_added"] = {
        "expected": sorted(expected_new),
        "actual": sorted(new_cols),
        "missing": list(missing_new),
        "pass": len(missing_new) == 0,
    }

    # Brand normalization
    checks["brand_norm"] = {
        "unique_values": sorted(df_out["brand_norm"].unique().tolist()),
        "pass": True,
    }

    # Product line
    checks["product_line"] = {
        "unique_values": sorted(df_out["product_line"].unique().tolist()),
        "pass": True,
    }

    # Fat level values
    valid_fat_levels = {"fat_free", "reduced_fat", "regular"}
    actual_fat_levels = set(df_out["fat_level"].unique())
    invalid_fat = actual_fat_levels - valid_fat_levels
    checks["fat_level"] = {
        "valid_values": sorted(valid_fat_levels),
        "actual_values": sorted(actual_fat_levels),
        "invalid": sorted(invalid_fat),
        "pass": len(invalid_fat) == 0,
    }

    # Identity flags are boolean
    flag_cols = ["is_organic", "is_gluten_free", "is_naturally_simple",
                 "is_sugar_free", "is_unsalted", "is_lactose_free",
                 "is_peanut_free", "is_plant_based", "is_reduced_sodium"]
    all_bool = all(df_out[col].dtype == bool for col in flag_cols)
    checks["identity_flags_boolean"] = {"pass": all_bool}

    # core_title not empty
    empty_core = (df_out["core_title"].str.strip() == "").sum()
    checks["core_title"] = {
        "empty_count": int(empty_core),
        "pass": empty_core == 0,
    }

    # identity_hash not empty
    empty_hash = (df_out["identity_hash"].str.strip() == "").sum()
    checks["identity_hash"] = {
        "empty_count": int(empty_hash),
        "pass": empty_hash == 0,
    }

    # No duplicate external_ids
    ext_dupes = df_out["external_id"].duplicated().sum()
    checks["external_id_uniqueness"] = {
        "duplicate_count": int(ext_dupes),
        "pass": ext_dupes == 0,
    }

    # Overall
    all_pass = all(c.get("pass", True) for c in checks.values())
    checks["overall"] = {"result": "PASS" if all_pass else "FAIL"}

    return checks


# ---------------------------------------------------------------------------
# Statistics
# ---------------------------------------------------------------------------

def build_statistics(df_in: pd.DataFrame, df_out: pd.DataFrame) -> dict:
    """Build Phase 2 statistics."""
    return {
        "version": VERSION,
        "timestamp": TIMESTAMP,
        "input": {
            "source": "phase1_output.parquet",
            "row_count": len(df_in),
            "column_count": len(df_in.columns),
        },
        "output": {
            "row_count": len(df_out),
            "column_count": len(df_out.columns),
            "columns_added": sorted(set(df_out.columns) - set(df_in.columns)),
        },
        "brand_normalization": {
            "input_brand_column": "brand_clean" if "brand_clean" in df_in.columns else "brand",
            "raw_brands": {str(k): int(v) for k, v in df_in.get("brand_clean", df_in["brand"]).value_counts().items()},
            "normalized_brands": {str(k): int(v) for k, v in df_out["brand_norm"].value_counts().items()},
            "product_lines": {str(k): int(v) for k, v in df_out["product_line"].value_counts().items()},
        },
        "identity_flags": {
            col: int(df_out[col].sum()) for col in [
                "is_organic", "is_gluten_free", "is_naturally_simple",
                "is_sugar_free", "is_unsalted", "is_lactose_free",
                "is_peanut_free", "is_plant_based", "is_reduced_sodium",
            ]
        },
        "fat_info": {
            "fat_level_distribution": {str(k): int(v) for k, v in df_out["fat_level"].value_counts().items()},
            "fat_percentage_nulls": int(df_out["fat_percentage"].isna().sum()),
            "fat_percentage_non_null": int(df_out["fat_percentage"].notna().sum()),
        },
        "flavour": {
            "products_with_flavour": int((df_out["flavour"].apply(len) > 0).sum()),
            "products_without_flavour": int((df_out["flavour"].apply(len) == 0).sum()),
        },
        "formulation": {
            "products_with_formulation": int((df_out["formulation"].apply(len) > 0).sum()),
            "products_without_formulation": int((df_out["formulation"].apply(len) == 0).sum()),
        },
        "core_title": {
            "unique_count": int(df_out["core_title"].nunique()),
        },
        "identity_hash": {
            "unique_count": int(df_out["identity_hash"].nunique()),
        },
    }


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main():
    log("Starting Phase 2")

    # Ensure output dirs exist
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    VALIDATION_DIR.mkdir(parents=True, exist_ok=True)
    STATISTICS_DIR.mkdir(parents=True, exist_ok=True)

    # Load Phase 1 output
    log(f"Loading Phase 1 output from: {INPUT_PATH}")
    df_in = pd.read_parquet(INPUT_PATH)
    log(f"Loaded: {df_in.shape[0]} rows, {df_in.shape[1]} columns")

    # Process
    df_out = process_phase2(df_in.copy())

    # Validate
    log("Validating output ...")
    validation = validate_phase2(df_in, df_out)

    # Statistics
    log("Building statistics ...")
    statistics = build_statistics(df_in, df_out)

    # Save outputs
    log("Saving outputs ...")
    df_out.to_parquet(OUTPUT_DIR / "phase2_output.parquet", index=False)
    log(f"  Saved phase2_output.parquet ({df_out.shape[0]} rows, {df_out.shape[1]} cols)")

    with open(VALIDATION_DIR / "phase2_validation.json", "w") as f:
        json.dump(validation, f, indent=2, default=str)
    log("  Saved phase2_validation.json")

    with open(STATISTICS_DIR / "phase2_statistics.json", "w") as f:
        json.dump(statistics, f, indent=2, default=str)
    log("  Saved phase2_statistics.json")

    # Summary
    log("")
    log("=== PHASE 2 COMPLETE ===")
    log(f"Input:  {df_in.shape[0]} rows, {df_in.shape[1]} columns")
    log(f"Output: {df_out.shape[0]} rows, {df_out.shape[1]} columns")
    log(f"Columns added: {sorted(set(df_out.columns) - set(df_in.columns))}")
    log(f"Validation: {validation['overall']['result']}")
    log("========================")

    return df_out, validation, statistics


if __name__ == "__main__":
    main()