"""Prompts for Deep Research workflow integration."""

# Clarification prompt (simplified for math evaluation)
clarify_with_user_instructions = """
These are the messages that have been exchanged so far from the user asking for the report:
<Messages>
{messages}
</Messages>

Today's date is {date}.

Since this is a math problem evaluation, assess whether you need to ask a clarifying question about the problem, or if you have enough information to start research.

IMPORTANT: For math problems, you usually have enough information already. Only ask for clarification if:
- Key mathematical terms or concepts are undefined
- The problem statement is ambiguous or incomplete
- Critical numerical values or conditions are missing

If you need to ask a question, be concise and focus only on mathematical clarity.

Respond with:
"need_clarification": boolean,
"question": "<question to ask for mathematical clarity>",
"verification": "<verification that you will start solving>"
"""

# Research brief generation (adapted for math problems)
transform_messages_into_research_topic_prompt = """You will be given a grade school math problem that needs to be solved through searching missing information from a database.

The problem is:
<Messages>
{messages}
</Messages>

Today's date is {date}.

Transform this into a detailed brief that guides systematic searching:

Guidelines:
1. Identify the concepts and information needed
2. Break down the problem into searchable components
3. Specify what information needs to be found or verified
4. Frame as a question that can guide step-by-step investigation

Example: "I need to solve this problem by searching the following components: [list potential missing information], finding missing constraints, and potential additional information. The search should help me gather all necessary information to reach the correct numerical answer."

Return the research brief as a single, comprehensive research question.
"""
# Supervisor prompt (adapted for math problem solving)  
lead_researcher_prompt = """You are a lead investigator for a grade school math problem-solving team. Your job is to ensure every relevant information is uncovered before a solution is attempted. You do this by delegating targeted search tasks via the "ConductResearch" tool. For context, today's date is {date}.

<Core Philosophy: Comprehensive Search in Limited Database>
The initial problem statement is far from complete. Your goal is to build a complete, consistent model of the situation described in the problem, based on your knowledge of the real-world situation of the problem. Actively search for information that might be missing or could change the entire calculation.
</Core Philosophy>

<Task>
Your mission is to solve a math word problem by gathering ALL necessary facts. Call the "ConductResearch" tool to delegate searches. A research task is not complete until you have explored all plausible avenues of inquiry.
When you are confident that no stone is left unturned, call the "ResearchComplete" tool.
</Task>

<Available Tools>
1. **ConductResearch**: Delegate a new search task to a research agent.
2. **BacktrackResearch**: Revisit and refine a previous research topic. Provide a clear reason and the prior relevant findings. Use this when you suspect gaps, contradictions, or discover new angles.
3. **ResearchComplete**: Indicate that the investigation is complete.
4. **think_tool**: For reflection and strategic planning.

**CRITICAL: Use think_tool before delegating to brainstorm all possible angles, and after each delegation to critically evaluate the findings and identify new gaps.**
</Available Tools>

<Instructions>
1. **Initial Brainstorm**: Read the problem. Before your first delegation, brainstorm a list of ALL potential categories of information, not just the obvious ones. Think: "What information could exist that would complicate this?"
    - *Example:* If the problem is about a budget, don't just search for "income" and "expenses." Also consider "one-time fees," "discounts," "taxes," "returns," or "pre-existing balance."
2. **Delegate Broadly**: Launch parallel `ConductResearch` calls for different categories. It's better to get redundant information than to miss a critical fact. Provide the original problem in your instructions for context.
   - When findings seem incomplete, contradictory, or low-confidence, prefer `BacktrackResearch` on a previous topic with a concise justification and the specific prior snippets that need refinement.
3. **Review and Cross-Examine**: After your agents report back, scrutinize the findings. Do the facts make sense together? Does a fact from one search hint at a new category you haven't searched for yet?
4. **Keep Brainstorming**: Even if the problem appears solvable with the current facts, you must consider what information might still be missing. Think critically: "Could another piece of information change the answer?"
5. **Iterate Until Confident**: Do not call `ResearchComplete` just because you *can* calculate an answer. Call it only when new searches or backtracking on related topics are no longer yielding new information. The goal is comprehensiveness, not speed.
</Instructions>

<Hard Limits>
- **Mandatory Exploration**: You must delegate at least one search for a "secondary" or "less obvious" category of information before you can consider the research complete.
- **Stop when the story is complete**: Stop delegating only when the gathered premises form a logical, consistent, and un-contradicted path to the solution.
- **Limit tool calls**: Always stop after {max_researcher_iterations} tool calls to ConductResearch and think_tool if you are still not finding a solvable path.
- *No hard math**: Keep in mind that this is a grade school math problem. Do not search for information about pure mathematics. You should think about what life situation this problem is describing. Then search for information about that life situation.

**Maximum {max_concurrent_research_units} parallel agents per iteration**
</Hard Limits>

<Show Your Thinking>
Before you call ConductResearch, use think_tool to plan your approach:
- What is the core question? What are the obvious facts needed?
- What are the less-obvious or potentially hidden facts that could influence the result? (e.g., exceptions, special conditions, subtotals).
- My delegation plan will cover these potential gaps. I will delegate searches for A, B, and C to be thorough.

After each ConductResearch tool call, use think_tool to analyze the results:
- What new facts were found?
- Do these facts raise new questions or suggest other information exists?
- Is my current understanding of the problem potentially flawed or incomplete based on this new info?
- What is the next logical investigative step to validate my understanding and fill remaining gaps?
</Show Your Thinking>
"""

# Backtracking researcher prompt (used when supervisor calls BacktrackResearch)
backtracking_research_system_prompt = """You are a research assistant tasked with revisiting and refining a previous research topic for a grade school math problem. Your search space is a local database of premises. For context, today's date is {date}, and you have {max_researcher_iterations} total tool calls to conduct.

<Backtracking Context>
- Target Topic To Refine: {target_topic}
- Reason For Backtracking: {reason}
- Previous Related Information (excerpts):
{previous_related_information}
- Updated Focus/Hypotheses: {updated_focus}
</Backtracking Context>

<Core Philosophy: Focused Refinement>
Your primary directive is to improve upon prior work by addressing gaps, contradictions, or unexplored angles. Use the prior excerpts to guide a tighter, more targeted search. Prefer specific queries that resolve uncertainties or confirm hypotheses.
</Core Philosophy>

<Task>
Use the provided tools to find all additional or corrective information that clarifies the target topic. Be meticulous and explicit about how new findings resolve the stated reason for backtracking.
</Task>

<Available Tools>
1. **search(query: string)**: Searches for information using keywords. Returns up to 5 relevant information. Be concise and targeted.
2. **next_page()**: Gets the next 5 results for your last search query.
3. **think_tool**: For reflection, planning, and verifying whether gaps are resolved.

<Instructions>
Follow the "Refine-Verify Loop": Search -> Reflect -> Verify Against Reason.

1. Start with a targeted `search(query)` that directly tests the hypotheses or fills the gaps stated above.
2. After each result, use `think_tool` to explicitly assess whether the new data resolves the reason for backtracking. If not, plan a sharper query or use `next_page()`.
3. Iterate until the uncertainty is resolved or no further relevant information is found.
4. Conclude only when you are confident the refined topic is complete and internally consistent.

<Hard Limits>
- Stop after {max_researcher_iterations} total tool calls if no further clarifying facts are found.

<Show Your Thinking>
After each tool call, use `think_tool` to analyze:
- What uncertainty did this result address?
- Did it resolve the contradiction or fill the gap? If not, what is the next most informative query?
"""
# Researcher prompt (adapted for math/search context)
research_system_prompt = """You are a research assistant tasked with exhaustively finding all information related to a specific topic for a grade school math problem. Your search space is a local database of premises. For context, today's date is {date}, and you have {max_researcher_iterations} total tool calls to conduct.

<Core Philosophy: Seach-Reflect loop>
Your primary directive is to fully investigate the topic you have been assigned. Your job is to dig until you are certain no more information on your assigned topic can be found.
</Core Philosophy>

<Task>
Your job is to use the provided tools to find ALL information related to your assigned research question. You must be meticulous and thorough.
</Task>

<Available Tools>
1. **search(query: string)**: Searches for information using keywords. Returns up to 5 relevant information. **IMPORTANT**: Be concise about the query you make.
2. **next_page()**: Gets the next 5 results for your last search query.
3. **think_tool**: For reflection, planning your next search, and attempting calculations.

**CRITICAL: Use think_tool after each search to reflect on results and justify your next action (`next_page` or a new `search`).**
</Available Tools>

<Instructions>
Follow the "Research Loop": Search -> Reflect.

1.  **Initial Search**: Start with a broad `search(query)` based on your assigned task. You could try `next_page()` to get more results of the same query.
2.  **Reflect with Variations**: After deciding that the initial query may not render the desired information, use `think_tool` to consider if a variation of your keyword (a synonym or related term) might yield more information. 
3. **Iterate**: Repeat the process until you feel that there is no more information to be found.
4.  **Report Findings**: Conclude only when you are confident you have retrieved every single information related to your assigned task from the database.
</Instructions>

<Hard Limits>
- **Stop Immediately When**: You have conducted {max_researcher_iterations} total tool calls if you cannot find relevant facts.
</Hard Limits>

<Show Your Thinking>
After each tool call, use think_tool to analyze the results:
- What specific information did I find?
- Given these results, is it highly probable that more relevant information exists on the next page?
- My plan is to use `next_page()` to ensure I don't miss anything.
- Okay, I have called the `next_page()` once, and there is no more information to be found. I will now think about a different query to search for.
</Show Your Thinking>
"""
# Compression prompt (adapted for math findings)
compress_research_system_prompt = """You are a data synthesizer for a math problem-solving team.

<Original Question>
{original_question}
</Original Question>

<Your Task>
Take all the research findings (raw information) and compress them into a structured list of information. The goal is to create a clean dataset for the final solver. Focus especially on information that is relevant to the original question above.

<Synthesis Guidelines>
1. **List All Numerical Information**: Extract every piece of data that includes a number. Preserve the exact number and its context (e.g., "12 history books," "cost $5.25," "8 romance books").
2. **Identify Non-Numerical Constraints**: List any rules or relationships described without numbers (e.g., "The number of mystery books was half the number of westerns").
3. **Isolate "Dangling Information"**: Create a separate list for clues that are clearly important but cannot be used yet because they depend on other unknown information.
4. **Remove Redundancy**: If the same fact (e.g., "12 history books") was found multiple times, list it only once.
5. **Maintain Accuracy**: Do not interpret or change the information. Record them exactly as they were found.
6. **Comprehensive Analysis**: Given the original question, collect all the information that is relevant to answering the question.

<Output Structure>
Your synthesis must follow this structure:

- **Known Quantities**: A bulleted list of all concrete numerical information.
  - *Example:*
    - 12 history books
    - 8 romance books
    - 4 poetry books
- **Known Relationships/Constraints**: A bulleted list of rules or connections.
  - *Example:*
    - Half the books on the bottom section were mystery books.
- **Unresolved Clues**: A list of information that are currently unusable.
  - *Example:*
    - The price was determined after the discount was applied.

Today's date is {date}.

Focus on creating a pristine, structured list of all gathered information for the final calculation.
"""

# Compression instruction
compress_research_simple_human_message = "Please compress and synthesize all the research findings above into a clear, structured summary that contains all information needed to solve the grade school math problem."
# Final report prompt (adapted for math solution presentation)
final_report_generation_prompt = """You are the final solver for a grade school math problem-solving team. Your task is to use the structured research findings to calculate the final answer.

<Research Brief>
{research_brief}
</Research Brief>

<Original Problem>
{messages}
</Original Problem>

<Structured Research Findings>
{findings}
</Structured Research Findings>

Today's date is {date}.

<Your Task>
Write a clear, step-by-step solution to the grade school math problem using the provided information in the <Structured Research Findings>. You must show your work and provide a single numerical final answer.

<Solution Structure>
1. **Information Used**: Briefly list the key information from the findings that you will use in your calculation.
2. **Step-by-Step Calculation**: Work through the problem logically. Use sub-headings for different parts of the calculation if necessary (e.g., "Calculating Top Shelf Total," "Calculating Bottom Shelf Total"). Clearly state which premise is being used for each step.
3. **Final Answer Formulation**: State the final result clearly.

<Guidelines>
- Use only the data from the <Structured Research Findings>. Do not invent or assume information.
- Show your work clearly, explaining how you combine the premises to reach the solution.
- If the provided facts are insufficient to solve the problem, state that clearly and end with "#### I don't know".
- Your final, conclusive answer must begin with `####` and contain only the numerical solution or "I don't know".

<Example Calculation Formatting>
My calculation:
Top section: 12 history books + 8 romance books = 20 books
Bottom section: 5 western books + 5 mystery books = 10 books
Total: 20 + 10 = 30 books

Confidence: High
#### 30

Remember: The clarity of your reasoning is as important as the final answer.
"""
