#!/usr/bin/env python3
"""AXE Docs Tools — Helper functions for Word document operations."""

import subprocess
import sys

def ensure_deps():
    for pkg in ["docx", "lxml"]:
        try:
            __import__(pkg)
        except ImportError:
            name = "python-docx" if pkg == "docx" else pkg
            subprocess.check_call([sys.executable, "-m", "pip", "install", name, "-q"])

ensure_deps()

from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH


def create_document(output_path, title, sections, page_width=8.5, page_height=11):
    """Create a Word document. Sections is a list of dicts with keys:
    type ('heading', 'paragraph', 'bullet', 'table', 'image'), level, text, data, path.
    """
    doc = Document()
    sec = doc.sections[0]
    sec.page_width = Inches(page_width)
    sec.page_height = Inches(page_height)
    sec.left_margin = Inches(1)
    sec.right_margin = Inches(1)

    doc.add_heading(title, level=0)

    for block in sections:
        btype = block.get("type", "paragraph")
        if btype == "heading":
            doc.add_heading(block["text"], level=block.get("level", 1))
        elif btype == "paragraph":
            p = doc.add_paragraph()
            run = p.add_run(block["text"])
            if block.get("bold"):
                run.bold = True
            if block.get("size"):
                run.font.size = Pt(block["size"])
        elif btype == "bullet":
            for item in block.get("items", []):
                doc.add_paragraph(item, style='List Bullet')
        elif btype == "table":
            data = block["data"]
            table = doc.add_table(rows=len(data), cols=len(data[0]), style='Table Grid')
            for i, row in enumerate(data):
                for j, cell_text in enumerate(row):
                    table.rows[i].cells[j].text = str(cell_text)
            # Bold header row
            for cell in table.rows[0].cells:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.bold = True
        elif btype == "image":
            doc.add_picture(block["path"], width=Inches(block.get("width", 4)))
            doc.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER

    doc.save(output_path)
    return output_path


def extract_text(docx_path):
    """Extract all text from a Word document."""
    doc = Document(docx_path)
    return "\n".join(p.text for p in doc.paragraphs if p.text.strip())


def replace_text(docx_path, replacements, output_path=None):
    """Replace text in a document. replacements is a dict of old->new."""
    doc = Document(docx_path)
    for paragraph in doc.paragraphs:
        for old, new in replacements.items():
            if old in paragraph.text:
                for run in paragraph.runs:
                    run.text = run.text.replace(old, new)
    # Also check tables
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    for old, new in replacements.items():
                        if old in paragraph.text:
                            for run in paragraph.runs:
                                run.text = run.text.replace(old, new)
    doc.save(output_path or docx_path)
    return output_path or docx_path


def docx_info(docx_path):
    """Get basic document metadata."""
    doc = Document(docx_path)
    props = doc.core_properties
    return {
        "paragraphs": len(doc.paragraphs),
        "tables": len(doc.tables),
        "sections": len(doc.sections),
        "author": props.author,
        "title": props.title,
        "created": str(props.created) if props.created else None,
    }
