AppInitDev
CÓDIGO FUENTE PÚBLICO

INTEGRAR_INDEX.py

Archivo real del paquete para implementar la función. Descárgalo del ZIP para editarlo; no contiene claves privadas.

#!/usr/bin/env python3
"""Añade solamente las tarjetas IA/MCP ausentes al index principal.
No modifica otras rutas ni estilos. Hace respaldo y es idempotente.
Uso: python AppInitDev_IA_MCP/INTEGRAR_INDEX.py
"""
import html
import re
import shutil
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlsplit

MOD=Path(__file__).resolve().parent
ROOT=MOD.parent
INDEX=ROOT/'index.html'
SOURCE=MOD/'PEGAR_EN_INDEX_PRINCIPAL.html'
GRID=re.compile(r'<div\b(?=[^>]*\bid\s*=\s*[\"\']aid-ecosystem-grid[\"\'])[^>]*>',re.I|re.S)
DIV=re.compile(r'</?div\b[^>]*>',re.I|re.S)
CARD=re.compile(r'<a\b(?P<attrs>[^>]*)>.*?</a\s*>',re.I|re.S)
HREF=re.compile(r'\bhref\s*=\s*([\"\'])(.*?)\1',re.I|re.S)
CLASS=re.compile(r'\bclass\s*=\s*([\"\'])(.*?)\1',re.I|re.S)

def route(attrs):
    h=HREF.search(attrs)
    if not h:return None
    c=CLASS.search(attrs)
    if not c or 'aid-resource' not in c.group(2).split():return None
    path=urlsplit(html.unescape(h.group(2).strip())).path
    if not path.startswith('/'):return None
    if path.endswith('index.html'):path=path[:-10]
    return path.rstrip('/')+'/' if path != '/' else '/'

def main():
    if not INDEX.is_file():raise SystemExit('No existe index.html junto a AppInitDev_IA_MCP.')
    original=INDEX.read_text(encoding='utf-8-sig')
    start=GRID.search(original)
    if not start:raise SystemExit('No encuentro #aid-ecosystem-grid. No se modificó index.html.')
    depth=1; end=None
    for m in DIV.finditer(original,start.end()):
        if m.group().startswith('</'):
            depth-=1
            if depth==0:
                end=m.start();break
        else:depth+=1
    if end is None:raise SystemExit('La cuadrícula HTML no tiene cierre. No se modificó index.html.')
    pattern=SOURCE.read_text(encoding='utf-8')
    planned={}
    for m in CARD.finditer(pattern):
        target=route(m.group('attrs'))
        if target:planned[target]=m.group(0)
    if len(planned)!=17:raise SystemExit('Se esperaban exactamente 17 tarjetas en la plantilla final.')
    middle=original[start.end():end]
    seen=set();removed=[]
    def dedupe(match):
        target=route(match.group('attrs'))
        if target and target in planned:
            if target in seen:
                removed.append(target);return ''
            seen.add(target)
        return match.group(0)
    updated=CARD.sub(dedupe,middle)
    missing=[p for p in planned if p not in seen]
    if missing:
        new='\n  <!-- AppInitDev IA/MCP: tarjetas faltantes, una por ruta -->\n'+'\n'.join(planned[p] for p in missing)+'\n'
        updated=new+updated
    result=original[:start.end()]+updated+original[end:]
    # El contador inicial es un fallback para JavaScript. Hacer que refleje el total real.
    count=len([m for m in CARD.finditer(updated) if route(m.group('attrs'))])
    counter=re.compile(r'(<[^>]*\bid\s*=\s*["\']aid-ecosystem-count["\'][^>]*>)(.*?)(</[^>]+>)',re.I|re.S)
    def update_count(m):
        return m.group(1)+f'\n              {count} secciones disponibles\n            '+m.group(3)
    result=counter.sub(update_count,result,count=1)
    if result==original:
        print('Index correcto: ya existen las 17 tarjetas sin duplicados. No se realizaron cambios.')
        return
    stamp=datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
    backup=MOD/'backups'/stamp/'index.html'
    backup.parent.mkdir(parents=True,exist_ok=True)
    shutil.copy2(INDEX,backup)
    INDEX.write_text(result,encoding='utf-8')
    print(f'Tarjetas nuevas añadidas: {len(missing)}. Duplicadas eliminadas: {len(removed)}.')
    print('Respaldo del index original:',backup)
    print('No se modificaron archivos de /pages/, CSS, sitemap ni .htaccess.')

if __name__=='__main__':main()