import docx
import re
import json

doc = docx.Document(r'c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\documentacion raul asencio\recetas\RECETARIO_DIGITALIZADO_RAUL_ASENCIO_v1 (1).docx')

tbl_map = {t._element: t for t in doc.tables}

recipes = []
current_recipe = None
current_family = ''

for child in doc.element.body:
    tag = child.tag.split('}')[-1]
    if tag == 'p':
        txt = ''.join(node.text for node in child.iter() if node.tag.endswith('t') and node.text).strip()
        if not txt:
            continue
        m = re.match(r'^(\d+)\s*·\s*(.+)$', txt)
        if m:
            num, name = m.groups()
            current_recipe = {
                'num': num,
                'name': name.strip(),
                'family': current_family,
                'source': '',
                'ingredients': [],
                'proceso': '',
                'notas': []
            }
            recipes.append(current_recipe)
        elif current_recipe:
            if txt in ['Ingredientes', 'Proceso escrito', 'Parámetros técnicos / rendimiento', 'Dudas / revisión']:
                current_recipe['_section'] = txt
            else:
                sec = current_recipe.get('_section', '')
                if sec == 'Proceso escrito':
                    if txt != 'No aparece proceso.':
                        current_recipe['proceso'] += (txt + ' ')
                elif sec in ['Parámetros técnicos / rendimiento', 'Dudas / revisión']:
                    current_recipe['notas'].append(f'{sec}: {txt}')
        else:
            if txt not in ['RECETARIO DIGITALIZADO', 'Raúl Asencio Pastelerías · v1 provisional', 'Índice maestro', 'Dudas pendientes y alertas'] and not txt.startswith('Criterio'):
                current_family = txt
    elif tag == 'tbl' and current_recipe:
        tbl = tbl_map.get(child)
        if tbl:
            first_row = [c.text.strip().lower() for c in tbl.rows[0].cells]
            if 'campo' in first_row:
                for row in tbl.rows:
                    cells = [c.text.strip() for c in row.cells]
                    if len(cells) >= 2 and cells[0].lower() == 'fuente':
                        current_recipe['source'] = cells[1]
            elif 'ingrediente' in first_row:
                for row in tbl.rows[1:]:
                    cells = [c.text.strip() for c in row.cells]
                    if cells and cells[0]:
                        ing = cells[0]
                        cant = cells[1] if len(cells) > 1 else ''
                        unidad = cells[2] if len(cells) > 2 else ''
                        obs = cells[3] if len(cells) > 3 else ''
                        current_recipe['ingredients'].append({
                            'ingrediente': ing,
                            'cantidad': cant,
                            'unidad': unidad,
                            'obs': obs
                        })

print(f'Total recipes parsed: {len(recipes)}')
for r in recipes[:10]:
    print(f"#{r['num']}: {r['name']} ({r['family']}) - {len(r['ingredients'])} ingr - Fuente: {r['source']}")

with open('parsed_recipes.json', 'w', encoding='utf-8') as f:
    json.dump(recipes, f, ensure_ascii=False, indent=2)

