"""xlsx_workbook：读写、多表、公式、doc_extract 共用导出。"""

from __future__ import annotations

from pathlib import Path

from openpyxl import Workbook

from aicd.tools.docs_convert import DocumentConverter
from aicd.tools.xlsx_workbook import (
    xlsx_extract_markdown_tables,
    xlsx_patch_workbook,
    xlsx_read_workbook,
    xlsx_write_workbook,
)


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


def test_xlsx_formula_write_and_read_modes(tmp_path: Path) -> None:
    p = tmp_path / "f.xlsx"
    r = xlsx_write_workbook(
        p,
        [{"name": "Data", "rows": [[1], ["=A1*3"]]}],
        policy_check=_policy,
    )
    assert r["ok"] is True
    raw = xlsx_read_workbook(p, policy_check=_policy, value_mode="raw")
    assert raw["ok"] is True
    rows = raw["sheets"][0]["rows"]
    assert rows[0][0].get("v") == 1
    assert rows[1][0].get("formula") == "=A1*3"

    cached = xlsx_read_workbook(p, policy_check=_policy, value_mode="cached")
    assert cached["sheets"][0]["rows"][1][0].get("v") is None

    both = xlsx_read_workbook(p, policy_check=_policy, value_mode="both")
    assert both["sheets"][0]["rows"][1][0].get("formula") == "=A1*3"


def test_xlsx_patch_and_multi_sheet_markdown(tmp_path: Path) -> None:
    p = tmp_path / "m.xlsx"
    wb = Workbook()
    wb.create_sheet("Second")
    wb["Sheet"]["B2"] = "x"
    wb.save(p)
    wb.close()

    pr = xlsx_patch_workbook(
        p,
        [
            {"sheet": "Sheet", "row": 1, "col": 1, "value": "=B2&\"!\""},
            {"sheet": "Second", "row": 2, "col": 1, "value": 42},
        ],
        policy_check=_policy,
    )
    assert pr["ok"] is True
    md = xlsx_extract_markdown_tables(
        p, ["Sheet", "Second"], stem="m", notes=[]
    )
    assert "Second" in md
    assert "x" in md or "42" in md

    conv = DocumentConverter(policy_check=_policy)
    outd = tmp_path / "mdout"
    res = conv.convert_document(str(p), str(outd), output_format="markdown")
    assert res.get("ok") is True
    written = Path(str(res["output_path"])).read_text(encoding="utf-8")
    assert "Second" in written


def test_xlsx_write_dict_formula(tmp_path: Path) -> None:
    p = tmp_path / "d.xlsx"
    r = xlsx_write_workbook(
        p,
        [{"name": "S", "rows": [[{"formula": "=1+1"}]]}],
        policy_check=_policy,
    )
    assert r["ok"] is True
    raw = xlsx_read_workbook(p, policy_check=_policy, value_mode="raw")
    assert raw["sheets"][0]["rows"][0][0].get("formula") == "=1+1"


def test_xlsx_read_sheet_filter(tmp_path: Path) -> None:
    p = tmp_path / "s.xlsx"
    wb = Workbook()
    wb.create_sheet("Only")
    wb.save(p)
    wb.close()
    rd = xlsx_read_workbook(
        p, policy_check=_policy, sheet_names=["Only"]
    )
    assert rd["ok"] is True
    assert len(rd["sheets"]) == 1
    assert rd["sheets"][0]["name"] == "Only"
