#!/usr/bin/env python3
"""Remove duplicate sections from entity pages after enrichment.

The enrichment created '## Growing Details' and '## Seed Viability' sections
but many pages already had this info in '## Growing Instructions' and '## Seed Storage'.

This script:
1. Removes '## Growing Details' if '## Growing Instructions' exists
2. Removes '## Seed Viability' if '## Seed Storage' exists
3. Keeps '## Yield' (this was genuinely new data)
"""
from pathlib import Path

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


def fix_entity(entity_path):
    """Remove duplicate sections."""
    content = entity_path.read_text()
    lines = content.split('\n')
    
    has_growing_instructions = any(line.startswith('## Growing Instructions') for line in lines)
    has_seed_storage = any(line.startswith('## Seed Storage') for line in lines)
    
    modified = False
    
    # Remove '## Growing Details' if '## Growing Instructions' exists
    if has_growing_instructions:
        new_lines = []
        skip = False
        for line in lines:
            if line.startswith('## Growing Details'):
                skip = True
                modified = True
            elif line.startswith('## ') and skip:
                skip = False
            elif not skip:
                new_lines.append(line)
        
        if modified:
            lines = new_lines

    # Remove '## Seed Viability' if '## Seed Storage' exists
    if has_seed_storage:
        new_lines = []
        skip = False
        for line in lines:
            if line.startswith('## Seed Viability'):
                skip = True
                modified = True
            elif line.startswith('## ') and skip:
                skip = False
            elif not skip:
                new_lines.append(line)
        
        if modified:
            lines = new_lines
    
    if modified:
        content = '\n'.join(lines)
        while '\n\n\n' in content:
            content = content.replace('\n\n\n', '\n\n')
        entity_path.write_text(content)
        return True
    
    return False


def main():
    fixed = 0
    for entity_path in ENTITIES_DIR.glob("*.md"):
        if 'curriculum' in entity_path.name:
            continue
        
        if fix_entity(entity_path):
            fixed += 1
            print(f"  ✓ {entity_path.stem}")
    
    print(f"\nFixed {fixed} entity pages")


if __name__ == "__main__":
    main()