#!/usr/bin/env python3
"""Enrich wiki entity pages with seed viability data."""
from pathlib import Path
from seed_viability_data import SEED_VIABILITY, build_viability_section

ENTITIES_DIR = Path(__file__).parent / "entities"


def enrich_entity(wiki_slug, viability_data):
    """Add Seed Viability 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 Seed Viability section
    if '## Seed Viability' in content:
        return False, "Section already exists"
    
    section = build_viability_section(viability_data)
    
    # Find insertion point: after ## Seed Storage
    lines = content.split('\n')
    insert_idx = None
    
    for i, line in enumerate(lines):
        if line.startswith('## Seed Storage'):
            # 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 before ## Related
        for i, line in enumerate(lines):
            if line.startswith('## Related'):
                insert_idx = i
                break
        else:
            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():
    from pathlib import Path
    wiki_slugs = [f.stem for f in ENTITIES_DIR.glob("*.md") if 'curriculum' not in f.name]
    
    enriched = 0
    skipped = 0
    unmatched = 0
    
    for wiki_slug in wiki_slugs:
        if wiki_slug in SEED_VIABILITY:
            success, msg = enrich_entity(wiki_slug, SEED_VIABILITY[wiki_slug])
            if success:
                enriched += 1
                print(f"  ✓ {wiki_slug}: {msg}")
            else:
                skipped += 1
                print(f"  - {wiki_slug}: {msg}")
        else:
            unmatched += 1
            print(f"  ? {wiki_slug}: No viability data")
    
    print(f"\n=== SUMMARY ===")
    print(f"Enriched: {enriched}")
    print(f"Skipped (already exists): {skipped}")
    print(f"Unmatched: {unmatched}")


if __name__ == "__main__":
    main()