"""工作区单轮 chat 与插件下 UUID 目录分配（不调 LLM）。"""

from __future__ import annotations

from pathlib import Path

import pytest

from aicd.config import PathPolicyConfig
from aicd.tools.path_policy import PathPolicy
from aicd.workspace_chat_once import (
    allocate_plugin_chat_workspace,
    resolve_host_chat_workspace,
)


def test_allocate_plugin_chat_workspace_creates_uuid_dir(tmp_path: Path) -> None:
    layout = {"plugins": tmp_path / "plugins"}
    layout["plugins"].mkdir()
    p = allocate_plugin_chat_workspace(layout, "my_plug")
    assert p.is_dir()
    assert p.parent.name == "_aicd_chat_spaces"
    assert p.parent.parent.name == "my_plug"


@pytest.mark.parametrize(
    "bad_id",
    ["", "_template", "9bad", "Bad", "a" * 70],
)
def test_allocate_plugin_chat_workspace_rejects_invalid_id(bad_id: str) -> None:
    layout = {"plugins": Path("/tmp")}
    with pytest.raises(ValueError):
        allocate_plugin_chat_workspace(layout, bad_id)


def _fake_ctx(tmp_path: Path) -> object:
    class _R:
        path_policy = PathPolicy(PathPolicyConfig(full_disk=True))

    class _C:
        layout = {"plugins": tmp_path / "plugins"}
        router = _R()

    _C.layout["plugins"].mkdir(parents=True)
    return _C()


def test_resolve_host_allocate_workspace(tmp_path: Path) -> None:
    ctx = _fake_ctx(tmp_path)
    wp, err = resolve_host_chat_workspace(
        ctx,  # type: ignore[arg-type]
        {"allocate_workspace": True, "plugin_id": "p1"},
    )
    assert err is None
    assert wp is not None
    assert wp.is_dir()
    assert (tmp_path / "plugins" / "p1") in wp.parents


def test_resolve_host_explicit_workspace(tmp_path: Path) -> None:
    ctx = _fake_ctx(tmp_path)
    wdir = tmp_path / "ws"
    wdir.mkdir()
    wp, err = resolve_host_chat_workspace(
        ctx,  # type: ignore[arg-type]
        {"workspace": str(wdir)},
    )
    assert err is None
    assert wp == wdir.resolve()


def test_resolve_host_missing_workspace_spec(tmp_path: Path) -> None:
    ctx = _fake_ctx(tmp_path)
    wp, err = resolve_host_chat_workspace(ctx, {})  # type: ignore[arg-type]
    assert wp is None
    assert err is not None
