import json
from pathlib import Path

from docx import Document
from docx.table import Table
from docx.text.paragraph import Paragraph
from openpyxl import load_workbook


TASK_DIR = Path(__file__).resolve().parent
SOURCES = {
    "previous_week": Path("/Users/jack/同步空间/cpt/05_经营管理与会议/005_日常管理/周例会（事业部层面）/2026年/数字技术中心&交付实施部周报 20260810.xlsx"),
    "july_monthly": Path("/Users/jack/同步空间/cpt/05_经营管理与会议/005_日常管理/周例会（事业部层面）/2026年/数字技术中心&交付实施部7 月月报.docx"),
    "current_w33": Path("/Users/jack/Downloads/数字技术中心与交付实施部周报_2026-W33_项目产品图文版_20260815.xlsx"),
}


def normalize(value):
    if value is None:
        return None
    if hasattr(value, "isoformat"):
        try:
            return value.isoformat()
        except Exception:
            pass
    return value


def extract_workbook(path: Path):
    wb = load_workbook(path, data_only=False)
    sheets = []
    for ws in wb.worksheets:
        nonempty_rows = []
        for row in ws.iter_rows():
            values = []
            for cell in row:
                value = normalize(cell.value)
                if ("账号" in ws.title or "密码" in ws.title) and cell.row >= 8 and cell.column in {5, 6} and value not in (None, ""):
                    value = "[已脱敏]"
                values.append(value)
            if any(value not in (None, "") for value in values):
                while values and values[-1] in (None, ""):
                    values.pop()
                nonempty_rows.append({"row": row[0].row, "values": values})
        sheets.append(
            {
                "name": ws.title,
                "max_row": ws.max_row,
                "max_column": ws.max_column,
                "merged_ranges": [str(item) for item in ws.merged_cells.ranges],
                "image_count": len(ws._images),
                "nonempty_rows": nonempty_rows,
            }
        )
    return {"path": str(path), "sheet_names": wb.sheetnames, "sheets": sheets}


def iter_docx_blocks(document):
    for child in document.element.body.iterchildren():
        if child.tag.endswith("}p"):
            yield Paragraph(child, document)
        elif child.tag.endswith("}tbl"):
            yield Table(child, document)


def extract_docx(path: Path):
    document = Document(path)
    blocks = []
    for block in iter_docx_blocks(document):
        if isinstance(block, Paragraph):
            text = block.text.strip()
            if text:
                blocks.append({"type": "paragraph", "style": block.style.name if block.style else None, "text": text})
        else:
            rows = []
            for row in block.rows:
                rows.append([cell.text.strip() for cell in row.cells])
            if any(any(cell for cell in row) for row in rows):
                blocks.append({"type": "table", "rows": rows})
    return {"path": str(path), "paragraph_count": len(document.paragraphs), "table_count": len(document.tables), "blocks": blocks}


def main():
    TASK_DIR.mkdir(parents=True, exist_ok=True)
    result = {
        "previous_week": extract_workbook(SOURCES["previous_week"]),
        "current_w33": extract_workbook(SOURCES["current_w33"]),
        "july_monthly": extract_docx(SOURCES["july_monthly"]),
    }
    output = TASK_DIR / "source-extract.json"
    output.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({
        "output": str(output),
        "previous_week_sheets": result["previous_week"]["sheet_names"],
        "current_w33_sheets": result["current_w33"]["sheet_names"],
        "monthly_blocks": len(result["july_monthly"]["blocks"]),
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
