from __future__ import annotations

from pathlib import Path

from aicd.tools.document_outline import extract_outline_from_text


def test_markdown_headings_lines_and_bytes() -> None:
    text = "# A\n\nx\n\n## B\n\ny\n"
    h = extract_outline_from_text(text, source_path="x.md", format_hint="markdown")
    assert len(h) == 2
    assert h[0]["level"] == 1 and h[0]["line"] == 1 and h[0]["text"] == "A"
    assert h[1]["level"] == 2 and h[1]["line"] == 5 and h[1]["text"] == "B"
    assert h[0]["byte_offset"] == 0
    assert isinstance(h[1]["byte_offset"], int)


def test_document_outline_tool_writes_json(tmp_path: Path) -> None:
    import asyncio

    from aicd.runtime import build_runtime

    md = tmp_path / "doc.md"
    md.write_text("# One\n\n## Two\n", encoding="utf-8")

    async def _go() -> None:
        ctx = await build_runtime(home=tmp_path / "home")
        ok, _ = ctx.set_ai_workspace(str(tmp_path))
        assert ok
        r = await ctx.router.run(
            "document_outline",
            {"path": "doc.md", "save_to_tmp": True},
        )
        assert r.get("ok") is True
        assert r.get("heading_count") == 2
        sp = r.get("saved_path")
        assert sp and Path(sp).is_file()
        await ctx.conn.close()

    asyncio.run(_go())


def test_document_outline_library_slug_writes_second_copy(tmp_path: Path) -> None:
    import asyncio

    from aicd.runtime import build_runtime

    md = tmp_path / "doc.md"
    md.write_text("# One\n\n## Two\n", encoding="utf-8")

    async def _go() -> None:
        ctx = await build_runtime(home=tmp_path / "home")
        ok, _ = ctx.set_ai_workspace(str(tmp_path))
        assert ok
        r = await ctx.router.run(
            "document_outline",
            {
                "path": "doc.md",
                "save_to_tmp": True,
                "library_doc_slug": "my-manual",
            },
        )
        assert r.get("ok") is True
        lp = r.get("library_saved_path")
        assert lp and Path(lp).is_file()
        assert "output" in lp.replace("\\", "/") and "library" in lp.replace("\\", "/")
        assert Path(lp).name == "doc.json"
        await ctx.conn.close()

    asyncio.run(_go())
