"""Discovery used to be a parallel contract that never fed ProjectRuntimeInvariants --
a user-named admin path established during discovery only ever existed as prose in
project-brief.md. apply_discovery_runtime_invariants closes that gap by running the
agreed specification through the same deterministic extractor codegen uses per-prompt."""
from __future__ import annotations

from types import SimpleNamespace

from src.workers.discovery_apply import apply_discovery_runtime_invariants


def test_admin_path_named_in_the_brief_becomes_a_sticky_invariant():
    project = SimpleNamespace(runtime_invariants=None)
    apply_discovery_runtime_invariants(
        project, "Build a support dashboard for staff at /be-admin, customers log in separately."
    )
    assert project.runtime_invariants["admin_panel_path"] == "/be-admin"
    assert project.runtime_invariants["source"] == "discovery"


def test_no_signal_in_the_brief_is_a_pure_noop():
    project = SimpleNamespace(runtime_invariants=None)
    apply_discovery_runtime_invariants(project, "A simple portfolio site with a contact section.")
    assert project.runtime_invariants is None


def test_discovery_source_out_sticks_a_later_ordinary_prompt():
    """The actual point of marking source="discovery": extract_runtime_invariants
    never downgrades an existing source="discovery" back to "prompt", so a later,
    unrelated codegen prompt can still add new signal without erasing that this
    project's admin path was deliberately agreed during discovery."""
    from src.domain.projects.runtime_invariants import extract_runtime_invariants, ProjectRuntimeInvariants

    project = SimpleNamespace(runtime_invariants=None)
    apply_discovery_runtime_invariants(project, "Admin panel lives at /be-admin.")
    assert project.runtime_invariants["source"] == "discovery"

    previous = ProjectRuntimeInvariants.model_validate(project.runtime_invariants)
    updated = extract_runtime_invariants("Also send emails via resend.", previous)
    assert updated.email_preference == "resend"
    assert updated.source == "discovery"


def test_existing_invariants_are_preserved_not_reset():
    project = SimpleNamespace(runtime_invariants={"admin_panel_path": "/be-admin", "source": "prompt"})
    apply_discovery_runtime_invariants(project, "A brief that never mentions admin paths at all.")
    # Nothing new extracted from this brief -- previous admin_panel_path/source untouched.
    assert project.runtime_invariants == {"admin_panel_path": "/be-admin", "source": "prompt"}
