"""Prompt construction helpers for SWE-bench examples."""

from __future__ import annotations

from typing import Optional

from .schema import SWEbenchExample


def _clamp(text: str, max_chars: Optional[int]) -> str:
    if max_chars is None:
        return text
    if max_chars <= 0:
        return ""
    if len(text) <= max_chars:
        return text
    if max_chars <= 3:
        return text[:max_chars]
    return text[: max_chars - 3] + "..."


def build_task_description(example: SWEbenchExample, max_chars: Optional[int] = None) -> str:
    """Create a compact task description used for embeddings."""
    return _clamp(example.task_description, max_chars)


def build_prompt(
    example: SWEbenchExample,
    *,
    include_hints: bool = True,
    include_repo: bool = True,
    max_chars: Optional[int] = None,
) -> str:
    """
    Build a deterministic prompt from a SWE-bench example.

    Args:
        example: SWE-bench instance.
        include_hints: whether to append hints_text if present.
        include_repo: whether to include repo and base_commit context.
        max_chars: optional clamp to keep prompts bounded.

    Returns:
        Prompt string ready for LLM submission.
    """
    lines: list[str] = []
    if include_repo:
        repo_line = f"Repository: {example.repo}"
        if example.base_commit:
            repo_line += f" @ {example.base_commit}"
        lines.append(repo_line)
    lines.append("Issue:")
    lines.append(example.problem_statement)
    if include_hints and example.hints_text:
        lines.append("Hints:")
        lines.append(example.hints_text)
    prompt = "\n".join(lines)
    return _clamp(prompt, max_chars)
