from docx import Document
from bs4 import BeautifulSoup
import sys

def html_table_to_docx(html_table, output_path):
    soup = BeautifulSoup(html_table, 'html.parser')
    table_tag = soup.find("table")
    doc = Document()

    if table_tag:
        rows = table_tag.find_all("tr")
        table = doc.add_table(rows=0, cols=len(rows[0].find_all(["td", "th"])))
        table.style = 'Table Grid'

        for row_tag in rows:
            row_cells = row_tag.find_all(["td", "th"])
            row = table.add_row().cells
            for i, cell in enumerate(row_cells):
                row[i].text = cell.get_text(strip=True)

    else:
        doc.add_paragraph("⚠ No se recibió una tabla válida.")

    doc.save(output_path)

if __name__ == "__main__":
    import json
    raw = sys.stdin.read()
    try:
        data = json.loads(raw)
        html_table = data.get("html", "")
        output_path = data.get("output_path", "output.docx")
        html_table_to_docx(html_table, output_path)
        print("OK")
    except Exception as e:
        print(f"ERROR: {e}")
