"""Pure PersonaSpec construction helpers.

Spec source: triage target #2 requires moving shell pure logic from
``shell/cli_utils.py::_synthesize_persona`` into ``core`` with contracts/doctests.
"""

from deal import post, pre
from typing import TypedDict


class InlinePersonaFields(TypedDict):
    """Fields required to construct an inline PersonaSpec."""

    id: str
    description: str
    prompt: str | None
    model: str


@pre(
    lambda model, system_prompt=None, persona_name="inline-agent", description=None: (
        isinstance(model, str)
        and (system_prompt is None or isinstance(system_prompt, str))
        and isinstance(persona_name, str)
        and (description is None or isinstance(description, str))
        and len(model.strip()) > 0
        and len(persona_name.strip()) > 0
        and (description is None or len(description.strip()) > 0)
    )
)
@post(lambda result: len(result["id"]) > 0)
@post(lambda result: len(result["description"]) > 0)
@post(lambda result: len(result["model"]) > 0)
def build_inline_persona_fields(
    model: str,
    system_prompt: str | None = None,
    persona_name: str = "inline-agent",
    description: str | None = None,
) -> InlinePersonaFields:
    """Build inline persona fields for shell-layer ``PersonaSpec`` construction.

    Args:
        model: Resolved model identifier.
        system_prompt: Optional inline system prompt. None means no system prompt.
        persona_name: Inline persona name.
        description: Optional persona description. Defaults to generated text.

    Returns:
        A dict with ``id``, ``description``, ``prompt``, and ``model`` keys.

    >>> fields = build_inline_persona_fields(
    ...     model="openai:gpt-5.2",
    ...     system_prompt="You are concise.",
    ... )
    >>> fields["id"]
    'inline-agent'
    >>> fields["model"]
    'openai:gpt-5.2'
    >>> fields["prompt"]
    'You are concise.'

    >>> # No system prompt
    >>> fields2 = build_inline_persona_fields(model="openai:gpt-5.2")
    >>> fields2["prompt"] is None
    True

    >>> build_inline_persona_fields("")  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    PreContractError: ...
    """
    resolved_description = description or f"Inline persona '{persona_name}'"
    return {
        "id": persona_name,
        "description": resolved_description,
        "prompt": system_prompt,
        "model": model,
    }


__all__ = ["build_inline_persona_fields"]
