"""Ask prompt builder for the OpenAI Agents SDK LerimOAIAgent."""

from __future__ import annotations

from typing import Any


def build_oai_ask_prompt(
	question: str,
	hits: list[dict[str, Any]],
	context_docs: list[dict[str, Any]],
	memory_root: str | None = None,
) -> str:
	"""Build the ask prompt for the OAI agent.

	Uses memory_search and read_file tools for memory retrieval.

	Args:
		question: The user's question.
		hits: Pre-fetched memory hits (frontmatter dicts with _body).
		context_docs: Pre-fetched context documents.
		memory_root: Path to memory directory for search guidance.
	"""
	context_lines = [
		(
			f"- {fm.get('id', '?')} conf={fm.get('confidence', '?')}: "
			f"{fm.get('title', '?')} :: {str(fm.get('_body', '')).strip()[:260]}"
		)
		for fm in hits
	]
	context_block = "\n".join(context_lines) or "(no relevant memories)"

	context_doc_lines = []
	for row in context_docs:
		doc_id = str(row.get("doc_id") or "")
		title = str(row.get("title") or "")
		body = str(row.get("body") or "").strip()
		snippet = " ".join(body.split())[:260]
		context_doc_lines.append(f"- {doc_id}: {title} :: {snippet}")
	context_doc_block = (
		"\n".join(context_doc_lines)
		if context_doc_lines
		else "(no context docs loaded)"
	)

	memory_guidance = ""
	if memory_root:
		memory_guidance = f"""
Memory root: {memory_root}
Layout:
- decisions/*.md — architecture and design decisions
- learnings/*.md — insights, procedures, pitfalls, preferences
- summaries/YYYYMMDD/HHMMSS/*.md — session summaries
Each file: YAML frontmatter (id, title, confidence, tags, kind, created) + markdown body.

Use the memory_search, read_file, and list_files tools to find and read memory files:
- memory_search(mode="keyword", query="...") to search across all memory files
- list_files(path="decisions/") or list_files(path="learnings/") to browse directories
- read_file(path="...") to get full content of a specific file
"""

	return f"""\
Answer the user question using your memory search tools.
- Use memory_search(mode="keyword") to find relevant memories in the memory root.
- Search project-first, then global fallback.
- Use read_file to retrieve full content when needed.
- Return evidence with file paths.
- If no relevant memories exist, say that clearly.
- Cite memory ids you used.
{memory_guidance}
Question:
{question}

Pre-fetched hints (may be incomplete — use memory_search for more):
{context_block}

Context docs:
{context_doc_block}
"""


def looks_like_auth_error(response: str) -> bool:
	"""Return whether response text indicates authentication failure."""
	text = str(response or "").lower()
	return (
		"failed to authenticate" in text
		or "authentication_error" in text
		or "oauth token has expired" in text
		or "invalid api key" in text
		or "unauthorized" in text
	)


if __name__ == "__main__":
	prompt = build_oai_ask_prompt(
		"how to deploy",
		[{"id": "mem-1", "confidence": 0.9, "title": "Deploy tips", "_body": "Use CI."}],
		[{"doc_id": "doc-1", "title": "CI Setup", "body": "Configure pipelines."}],
	)
	assert "how to deploy" in prompt
	assert "mem-1" in prompt
	assert "memory_search" in prompt
	assert "explore()" not in prompt

	prompt_mr = build_oai_ask_prompt("test", [], [], memory_root="/tmp/test/memory")
	assert "Memory root: /tmp/test/memory" in prompt_mr
	assert "memory_search" in prompt_mr
	assert "decisions/*.md" in prompt_mr

	print("oai_ask prompt: all self-tests passed")
