"""Tests for auto-compile improvement actions."""

from __future__ import annotations

from compiler.sources.discover import SourceCandidate
from compiler.stages.improve import improve_sources_config


async def test_improve_adds_public_domain_candidates_and_marks_approved():
    async def fake_discover(name: str, include_podcasts: bool = False):
        assert name == "Ada Lovelace"
        assert include_podcasts is False
        return [
            SourceCandidate(
                source_type="book",
                title="Public Book",
                origin_url="https://www.gutenberg.org/ebooks/123",
                rights="public-domain",
                fetch_type="gutenberg",
                source_id="gutenberg-123",
                fetch_config={"gutenberg_id": 123},
            ),
            SourceCandidate(
                source_type="article",
                title="Modern Article",
                origin_url="https://example.com/article",
                rights="fair-use-excerpt",
            ),
        ]

    config, actions = await improve_sources_config(
        {"slug": "ada-lovelace", "display_name": "Ada Lovelace", "sources": []},
        {"groundedness": 0.8, "style_match": 0.3, "misattribution": 0},
        iteration=1,
        discover_fn=fake_discover,
    )

    assert "added 1 public-domain source candidate(s)" in actions
    assert [s["id"] for s in config["sources"]] == ["gutenberg-123"]
    assert config["sources"][0]["approved"] is True


async def test_improve_deduplicates_existing_sources():
    async def fake_discover(name: str, include_podcasts: bool = False):
        return [
            SourceCandidate(
                source_type="book",
                title="Public Book",
                origin_url="https://www.gutenberg.org/ebooks/123",
                rights="public-domain",
                fetch_type="gutenberg",
                source_id="gutenberg-123",
                fetch_config={"gutenberg_id": 123},
            )
        ]

    original = {
        "slug": "ada-lovelace",
        "display_name": "Ada Lovelace",
        "sources": [{"id": "gutenberg-123", "approved": True}],
    }

    config, actions = await improve_sources_config(
        original,
        {"groundedness": 0.8, "style_match": 0.3, "misattribution": 0},
        iteration=1,
        discover_fn=fake_discover,
    )

    assert actions == []
    assert len(config["sources"]) == 1
    assert len(original["sources"]) == 1


async def test_improve_tweaks_retrieval_when_groundedness_low():
    config, actions = await improve_sources_config(
        {
            "slug": "ada-lovelace",
            "display_name": "Ada Lovelace",
            "sources": [],
            "index": {"retrieval_top_k": 4, "chunk_overlap": 64},
        },
        {"groundedness": 0.2, "style_match": 0.8, "misattribution": 0},
        iteration=2,
        discover_fn=lambda name, include_podcasts=False: [],
    )

    assert config["index"]["retrieval_top_k"] == 6
    assert config["index"]["chunk_overlap"] == 80
    assert config["auto"]["last_iteration"] == 2
    assert any("tweaked retrieval/index params" in action for action in actions)


async def test_improve_noops_when_scores_pass():
    config, actions = await improve_sources_config(
        {"slug": "ada-lovelace", "display_name": "Ada Lovelace", "sources": []},
        {"groundedness": 0.8, "style_match": 0.7, "misattribution": 0},
        iteration=1,
        discover_fn=lambda name, include_podcasts=False: [],
    )

    assert actions == []
    assert config["sources"] == []
