#!/usr/bin/env python3
"""Enrich wiki entity pages with WooCommerce product data.

Adds ## Growing Details section with:
- Germination time & temperature
- Days to harvest
- Special techniques (soaking, stratification, start indoors, etc.)
"""
import json
import re
from pathlib import Path

DATA_FILE = Path(__file__).parent / "extracted_growing_data.json"
PRODUCTS_FILE = Path(__file__).parent / "woo_products.json"
ENTITIES_DIR = Path(__file__).parent / "entities"


def slug_match(woo_slug, wiki_slug):
    """Match WooCommerce slug to wiki entity slug.
    
    Woo slugs have suffixes like '-seeds', '-squash-seeds', etc.
    Wiki slugs are cleaner like 'dark-green-zucchini-squash'.
    """
    # Simple: remove trailing '-seeds' or '-seed'
    cleaned = re.sub(r'-seeds?$', '', woo_slug, flags=re.I)
    if cleaned == wiki_slug:
        return True
    
    # Check if wiki slug is a substring of woo slug (handles compound names)
    if wiki_slug in woo_slug:
        return True
    
    # Check if woo slug starts with wiki slug
    if woo_slug.startswith(wiki_slug + '-'):
        return True
    
    return False


def build_slug_map():
    """Build mapping from wiki slugs to Woo data."""
    with open(DATA_FILE) as f:
        woo_data = json.load(f)
    
    wiki_slugs = [f.stem for f in ENTITIES_DIR.glob("*.md") if 'curriculum' not in f.name]
    
    mapping = {}
    for wiki_slug in wiki_slugs:
        for woo_slug, data in woo_data.items():
            if slug_match(woo_slug, wiki_slug):
                mapping[wiki_slug] = data
                break
    
    return mapping


def format_growing_section(data):
    """Format extracted data as wiki section."""
    lines = ["## Growing Details"]
    
    if 'germination_days' in data:
        temp = f" at {data['germination_temp']}°F" if 'germination_temp' in data else ""
        lines.append(f"- **Germination:** {data['germination_days']}{temp}")
    
    if 'harvest_days' in data:
        lines.append(f"- **Days to Harvest:** {data['harvest_days']} days")
    
    if 'sowing_depth' in data:
        lines.append(f"- **Sowing Depth:** {data['sowing_depth']}\"")
    
    if 'spacing' in data:
        lines.append(f"- **Spacing:** {data['spacing']}\"")
    
    if 'seed_count' in data:
        lines.append(f"- **Seeds per Packet:** ~{data['seed_count']}")
    
    if 'techniques' in data:
        technique_map = {
            'soaking': 'Soak seeds overnight before sowing',
            'scarification': 'Scarify seed coat before sowing',
            'stratification': 'Cold stratification required',
            'light_required': 'Do not cover — sow on surface (light required for germination)',
            'start_indoors': 'Start indoors 3-4 weeks before last frost',
            'succession_planting': 'Succession planting recommended for continuous harvest',
        }
        lines.append("- **Special Notes:**")
        for t in data['techniques']:
            label = technique_map.get(t, t)
            lines.append(f"  - {label}")
    
    if len(lines) <= 1:
        return None
    
    return "\n".join(lines) + "\n"


def enrich_entity(wiki_slug, data):
    """Add Growing Details section to entity page."""
    entity_path = ENTITIES_DIR / f"{wiki_slug}.md"
    
    if not entity_path.exists():
        return False, "Entity page not found"
    
    content = entity_path.read_text()
    
    # Check if already has Growing Details section
    if '## Growing Details' in content:
        return False, "Section already exists"
    
    section = format_growing_section(data)
    if not section:
        return False, "No data to add"
    
    # Find insertion point: after ## Overview or ## Key Details
    # Insert before the first ## that comes after overview/details
    lines = content.split('\n')
    insert_idx = None
    
    for i, line in enumerate(lines):
        if line.startswith('## Overview') or line.startswith('## Key Details'):
            # Find end of this section
            for j in range(i + 1, len(lines)):
                if lines[j].startswith('## '):
                    insert_idx = j
                    break
            else:
                insert_idx = len(lines)
            break
    
    if insert_idx is None:
        # Insert at end
        insert_idx = len(lines)
    
    lines.insert(insert_idx, '')
    lines.insert(insert_idx + 1, section.strip())
    
    new_content = '\n'.join(lines)
    entity_path.write_text(new_content)
    return True, "Enriched"


def main():
    mapping = build_slug_map()
    
    print(f"=== SLUG MAPPING ({len(mapping)} matches) ===")
    for wiki_slug, data in sorted(mapping.items()):
        print(f"  {wiki_slug}: {list(data.keys())}")
    
    print(f"\n=== ENRICHING ===")
    enriched = 0
    skipped = 0
    
    for wiki_slug, data in sorted(mapping.items()):
        success, msg = enrich_entity(wiki_slug, data)
        if success:
            enriched += 1
            print(f"  ✓ {wiki_slug}: {msg}")
        else:
            skipped += 1
            print(f"  - {wiki_slug}: {msg}")
    
    print(f"\n=== SUMMARY ===")
    print(f"Enriched: {enriched}")
    print(f"Skipped: {skipped}")
    print(f"Unmatched wiki entities: {sum(1 for f in ENTITIES_DIR.glob('*.md') if 'curriculum' not in f.name and f.stem not in mapping)}")


if __name__ == "__main__":
    main()