"""Build user-message sections for voice transcript + attached files."""
from __future__ import annotations

import os
from typing import Optional
from uuid import UUID

_DATASET_EXTENSIONS = {".csv", ".json", ".jsonl", ".ndjson"}


def _looks_like_dataset(filename: str) -> bool:
    return os.path.splitext(filename or "")[1].lower() in _DATASET_EXTENSIONS


def build_multimodal_prompt_appendix(
    *,
    voice_transcript: Optional[str] = None,
    copied_files: Optional[list[tuple[str, str]]] = None,
    unattached_descriptions: Optional[list[tuple[str, str]]] = None,
    repo_subdir: Optional[str] = None,
) -> str:
    """Return markdown to append to the user's text prompt.

    ``copied_files``: list of (disk_filename, kind) after copy into repo.
    ``unattached_descriptions``: when no repo copy (API-only codegen), (original_name, kind).
    ``repo_subdir``: e.g. ``p2hs/prompt-media/{run_id}`` for Cursor to open files.
    """
    parts: list[str] = []

    vt = (voice_transcript or "").strip()
    if vt:
        parts.append("## Voice transcript (speech-to-text)\n" + vt)

    if copied_files and repo_subdir:
        lines = [
            "## Attached files",
            "The user included the following files. They are available in the repository under "
            f"`{repo_subdir}/`:",
            "",
        ]
        for name, kind in copied_files:
            lines.append(f"- `{name}` ({kind})")
        lines.append("")
        if any(_looks_like_dataset(name) for name, _kind in copied_files):
            lines.extend(
                [
                    "Structured data attachments (CSV/JSON/JSONL/NDJSON) may be seed datasets "
                    "for the app.",
                    "Inspect their columns and sample rows. If the app should query or mutate "
                    "that data at runtime, model the entity schema and use the "
                    "PlatformBackendCapabilities `data_import` / record engine flow instead of "
                    "hardcoding the dataset into frontend source.",
                ]
            )
        else:
            lines.append(
                "Use these files as visual, audio, or document context when implementing the "
                "request."
            )
        parts.append("\n".join(lines))

    elif unattached_descriptions:
        lines = [
            "## Attached files (names only)",
            "The user attached files, but this run does not have a repo checkout; filenames "
            "for context:",
            "",
        ]
        for name, kind in unattached_descriptions:
            lines.append(f"- {name} ({kind})")
        parts.append("\n".join(lines))

    if not parts:
        return ""
    return "\n\n" + "\n\n".join(parts)
