"""style_reference_scan、office_write（xlsx/pptx）、docx 样式 profile。"""

from __future__ import annotations

from pathlib import Path

from openpyxl import load_workbook
from pptx import Presentation

from aicd.tools.office_write import pptx_compose, pptx_inspect_template, xlsx_write_workbook
from aicd.tools.style_reference import load_docx_style_profile, scan_style_reference


def _policy(p: Path) -> None:
    return None


def test_load_docx_style_profile(tmp_path: Path) -> None:
    y = tmp_path / "s.yaml"
    y.write_text(
        "docx_defaults:\n  default_east_asia_font: 楷体\n  default_body_font_pt: 11\n"
        "notes: |\n  标题居中\n",
        encoding="utf-8",
    )
    r = load_docx_style_profile(y, policy_check=_policy)
    assert r["ok"] is True
    assert r["docx_defaults"]["default_east_asia_font"] == "楷体"
    assert r["docx_defaults"]["default_body_font_pt"] == 11
    assert "标题居中" in r["notes"]


def test_scan_style_reference_dir(tmp_path: Path) -> None:
    d = tmp_path / "ref"
    d.mkdir()
    (d / "tone.md").write_text("# Brand\nUse formal Chinese.\n", encoding="utf-8")
    r = scan_style_reference(d, policy_check=_policy)
    assert r["ok"] is True
    assert r["entry_count"] >= 1
    assert "formal" in r["style_digest"] or "Brand" in r["style_digest"]


def test_xlsx_write_workbook_roundtrip(tmp_path: Path) -> None:
    p = tmp_path / "book.xlsx"
    r = xlsx_write_workbook(
        p,
        [
            {"name": "S1", "headers": ["a", "b"], "rows": [["1", "2"]]},
            {"name": "S2", "rows": [["x"]]},
        ],
        policy_check=_policy,
    )
    assert r["ok"] is True
    wb = load_workbook(p)
    assert "S1" in wb.sheetnames and "S2" in wb.sheetnames
    assert wb["S1"].cell(1, 1).value == "a"
    assert wb["S1"].cell(2, 1).value == "1"


def test_pptx_compose_and_inspect(tmp_path: Path) -> None:
    out = tmp_path / "deck.pptx"
    r = pptx_compose(
        out,
        [
            {"layout_index": 1, "title": "Hi", "bullets": ["a", "b"]},
        ],
        policy_check=_policy,
    )
    assert r["ok"] is True
    assert out.is_file()
    prs = Presentation(str(out))
    assert len(prs.slides) == 1

    ins = pptx_inspect_template(out, policy_check=_policy)
    assert ins["ok"] is True
    assert ins["layout_count"] >= 1
