"""Tests for doc-gen task type."""

from unittest.mock import MagicMock
from milco.core.run_context import RunContext
from milco.core.artifacts import write_artifact
from milco.tasks.registry import get_task, _registry

_registry.pop("doc-gen", None)
import milco.tasks.doc_gen  # noqa: F401, E402  # force real registration

FAKE_README = """\
# My Project

A great project.

## Installation

pip install myproject

## Usage

Run it.

## Project Structure

Files and stuff.
"""


def _make_ctx(tmp_path, llm_response=FAKE_README):
    contract = tmp_path / "TASK_CONTRACT.md"
    contract.write_text(
        "# Task Contract\n\n"
        "## Task Type\n\ndoc-gen\n\n"
        "## Goal\n\nGenerate README.\n\n"
        "## Scope\n\nRoot README only.\n\n"
        "## Out of scope\n\nNothing.\n\n"
        "## Success Criteria\n\nREADME.md exists.\n\n"
        "## Constraints\n\nNone.\n\n"
        "## Approvals required\n\nCONFIRM APPLY\n\n"
        "## Notes\n\nNone.\n",
        encoding="utf-8",
    )
    mock_llm = MagicMock()
    mock_llm.complete.return_value = llm_response
    ctx = RunContext(
        repo_root=tmp_path,
        run_id="test-docgen",
        apply_mode=False,
        contract_path=str(contract),
        task_type="doc-gen",
        llm=mock_llm,
    )
    write_artifact(ctx, "evidence.md", "# Evidence\n\nSome evidence.\n")

    (tmp_path / "pyproject.toml").write_text(
        '[project]\nname = "myproject"\nversion = "0.1.0"\n',
        encoding="utf-8",
    )
    return ctx


def test_doc_gen_registered():
    cls = get_task("doc-gen")
    assert cls is not None
    assert cls.needs_llm is True


def test_doc_gen_calls_llm(tmp_path):
    ctx = _make_ctx(tmp_path)
    task = get_task("doc-gen")()
    result = task.fix(ctx)
    ctx.llm.complete.assert_called_once()
    assert result.success is True


def test_doc_gen_writes_patches_diff(tmp_path):
    ctx = _make_ctx(tmp_path)
    task = get_task("doc-gen")()
    task.fix(ctx)
    diff_path = ctx.artifact_path("patches.diff")
    assert diff_path.exists()
    content = diff_path.read_text(encoding="utf-8")
    assert "README.md" in content


def test_doc_gen_applies_in_apply_mode(tmp_path):
    ctx = _make_ctx(tmp_path)
    ctx.apply_mode = True
    task = get_task("doc-gen")()
    result = task.fix(ctx)
    assert result.applied is True
    readme = tmp_path / "README.md"
    assert readme.exists()
    assert "My Project" in readme.read_text(encoding="utf-8")


def test_doc_gen_dry_run_no_apply(tmp_path):
    ctx = _make_ctx(tmp_path)
    ctx.apply_mode = False
    task = get_task("doc-gen")()
    result = task.fix(ctx)
    assert result.applied is False
    assert not (tmp_path / "README.md").exists()
