from langchain.prompts import PromptTemplate

# Select prompt - for choosing which leaf node to expand next in hierarchical planning
select_prompt = PromptTemplate.from_template(
"""You are using a hierarchical thinking approach to solve a travel planning query. This approach uses a tree-like structure where complex problems are broken down into manageable sub-components. You need to select which leaf node (most specific component) to expand next.

Query: {query}

Current Hierarchical Planning Structure:
{current_tree}

Available Leaf Nodes to Expand:
{leaves}

Please select the index of the leaf node that should be expanded next. Consider:
1. Which expansion would provide the most critical information for solving the query
2. Which node represents the most urgent planning concern that affects the overall solution
3. Which expansion would best follow the divide-and-conquer strategy by breaking complex constraints into manageable pieces
4. Which node expansion would help manage multiple sub-tasks more effectively

Choose the index number of the leaf node to expand next (just return the number)."""
)

# Expand prompt - for expanding a selected node into sub-components
expand_prompt = PromptTemplate.from_template(
"""You are using a hierarchical thinking approach to solve a travel planning query. This method employs a tree-like planning structure that breaks complex problems into smaller, manageable sub-components using a divide-and-conquer strategy.

Query: {query}

Current Hierarchical Planning Structure:
{current_tree}

Selected Node to Expand: {selected_node}

Please expand this node into its relevant sub-components. Consider:
1. What are the key sub-aspects of this planning component that need separate attention?
2. How can this be broken down using divide-and-conquer strategy to handle multiple constraints simultaneously?
3. What specific constraints, requirements, or considerations apply to this component?
4. How can each sub-component be managed as an independent sub-task while maintaining coherence?
5. What dependencies exist between different sub-components?

Provide the expansion as a list of sub-components in the format: [component1][component2][component3]"""
)

# Decide prompt - for making decisions in the planning process
decide_prompt = PromptTemplate.from_template(
"""You are using a hierarchical thinking approach to make a decision in the travel planning process. This approach systematically considers multiple constraints and manages various sub-tasks to ensure optimal decision-making.

Query: {query}

Current Context: {context}

Options to Consider: {options}

Please make a decision based on:
1. The requirements and constraints specified in the query
2. The current planning context and how it affects other components
3. The feasibility and quality of each option within the constraint framework
4. The overall coherence and consistency of the plan across all sub-tasks
5. How this decision impacts the management of other sub-components
6. The divide-and-conquer principle - ensuring this decision doesn't create conflicts in other areas

Provide your decision with detailed reasoning that shows how you've considered the hierarchical implications."""
)

# Execute prompt - for generating the thinking process based on the solution strategy
execute_prompt = PromptTemplate.from_template(
"""You are using a hierarchical thinking approach to generate a comprehensive planning process for travel arrangements. This method uses a tree-like solution structure that systematically breaks down complex planning challenges using divide-and-conquer strategies.

Available Information:
{given_information}

Query: {query}

Solution Strategy (Hierarchical Planning Structure):
{solution_strategy}

Based on the hierarchical solution strategy above, please generate a detailed thinking process that:

1. **Systematically analyzes each component** in the strategy tree, working through branches methodically
2. **Identifies and handles constraints** for each aspect, ensuring diverse requirements are satisfied
3. **Makes specific decisions** for transportation, accommodation, attractions, and dining while managing inter-dependencies
4. **Ensures consistency and coherence** across all planning elements and sub-tasks
5. **Validates feasibility** of the overall plan through constraint checking
6. **Manages multiple sub-tasks** effectively, ensuring each component contributes to the whole
7. **Applies divide-and-conquer principles** to handle complex multi-faceted requirements

Think through each branch of the strategy tree systematically. For each node, consider how it relates to parent and sibling nodes. Provide detailed reasoning for your planning decisions that shows hierarchical thinking. Address budget constraints, time limitations, preferences, and practical considerations as interconnected constraints rather than isolated factors.

Your thinking process should demonstrate how the hierarchical approach helps organize and manage the complexity of travel planning."""
)

# Convert prompt - for converting strings to proper format
convert_prompt = PromptTemplate.from_template(
"""Please convert the following string into the proper bracketed format for hierarchical planning structure.

String to convert: {str_to_convert}

Convert this into the format: [component1][component2][component3]

Ensure each component is:
1. Clearly defined and specific to enable focused sub-task management
2. Properly formatted with brackets for hierarchical structure representation
3. Logically organized to support divide-and-conquer strategy
4. Relevant to travel planning with clear constraint boundaries
5. Designed to support independent analysis while maintaining overall coherence

Provide only the converted format."""
)

# Tree convert prompt - for converting tree structure to different format
tree_convert_prompt = PromptTemplate.from_template(
"""Please convert the following hierarchical planning structure into a more readable format.

Tree Structure:
{tree_to_convert}

Convert this tree into a clear, hierarchical representation that shows:
1. The main planning categories and their constraint boundaries
2. The sub-components under each category and their inter-dependencies
3. The logical structure and relationships between different levels
4. The complete planning strategy using divide-and-conquer principles
5. How different sub-tasks are organized and managed within the hierarchy
6. The flow of constraint handling from high-level to specific requirements

Format it in a way that clearly demonstrates the hierarchical thinking approach and systematic decomposition strategy."""
)

# Plan generation prompt - for generating the final travel plan
plan_generation_prompt = PromptTemplate.from_template(
"""You are generating the final travel plan based on your hierarchical thinking process. This systematic approach has broken down the complex planning challenge into manageable components using divide-and-conquer strategies.

Query: {query}

Thinking Process:
{thinking_process}

Based on the comprehensive hierarchical thinking process above, please generate a detailed travel plan that includes:

1. **Daily Itinerary**: Day-by-day schedule with specific times, showing how sub-tasks integrate
2. **Transportation**: Detailed transport arrangements between locations with constraint considerations
3. **Accommodation**: Specific hotels/lodging with booking details that satisfy identified requirements
4. **Attractions**: Selected attractions with visiting schedules that respect multiple constraints
5. **Dining**: Restaurant selections for breakfast, lunch, and dinner that complement other activities
6. **Budget Breakdown**: Cost estimation for each component showing constraint adherence

The plan should demonstrate:
- **Systematic Organization**: All aspects addressed through hierarchical breakdown
- **Constraint Satisfaction**: Multiple requirements handled simultaneously
- **Sub-task Integration**: Individual components work together seamlessly
- **Feasible Logistics**: Realistic timing and practical arrangements
- **Detailed Specifications**: Specific names, locations, and arrangements
- **Optimized Coherence**: Best use of time and resources across all levels of planning

Format the plan as a detailed day-by-day itinerary that reflects the systematic approach used in the thinking process."""
)


# New: Support user preferences for expanded prompt
trip_expand_prompt = PromptTemplate.from_template(
"""You are using a hierarchical thinking approach to solve a travel planning query. This method employs a tree-like planning structure that systematically decomposes complex problems into manageable sub-components using divide-and-conquer strategies.

Query: {query}

Current Hierarchical Planning Structure:
{current_tree}

Selected Node to Expand: {selected_node}

User Preferences: {user_preferences}

Please expand this node into its relevant sub-components. Consider:
1. What are the key sub-aspects of this planning component that require separate constraint handling?
2. How can this be broken down using divide-and-conquer strategy to manage multiple user preferences simultaneously?
3. What specific constraints, requirements, or user preferences apply to this component?
4. How can each sub-component be treated as an independent sub-task while ensuring overall coherence?
5. What dependencies exist between this component and user preferences?

Provide the expansion as a list of sub-components in the format: [component1][component2][component3]"""
)

# New: Support new data format for execution prompt
trip_execute_prompt = PromptTemplate.from_template(
"""You are using a hierarchical thinking approach to generate a comprehensive planning process for travel arrangements. This systematic method uses a tree-like solution structure to break down complex planning challenges through divide-and-conquer strategies while managing multiple constraints and user preferences.

Available Information:
{given_information}

Query: {query}

User Preferences: {user_preferences}

Solution Strategy (Hierarchical Planning Structure):
{solution_strategy}

Based on the hierarchical solution strategy above, please generate a detailed thinking process that:

1. **Systematically analyzes each component** in the strategy tree, processing branches methodically
2. **Identifies and manages constraints** for each aspect, including user preferences as constraint factors
3. **Makes specific decisions** for transportation, accommodation, and attractions while handling inter-dependencies
4. **Ensures consistency and coherence** across all planning elements and sub-tasks
5. **Validates feasibility** of the overall plan through comprehensive constraint checking
6. **Applies divide-and-conquer principles** to handle complex multi-faceted requirements efficiently
7. **STRICT INFORMATION COMPLIANCE**: Every hotel, attraction, and transportation option must be selected **exclusively** from the items explicitly listed in "Available Information". No fabrication or external options are permitted.

Think through each branch of the strategy tree systematically. For each node, demonstrate how it relates to parent and sibling nodes in the hierarchy. Provide detailed reasoning that shows hierarchical constraint management. Address budget limitations, time constraints, user preferences, and practical considerations as interconnected constraint factors rather than isolated requirements.

Your thinking process should demonstrate how the hierarchical approach effectively organizes and manages the complexity of travel planning while satisfying multiple simultaneous constraints."""
)

trip_select_prompt = PromptTemplate.from_template(
"""You are using a hierarchical thinking approach to solve a travel planning query. This approach employs a tree-like structure where complex problems are systematically broken down into manageable sub-components. You need to select which leaf node (most specific component) to expand next.

Query: {query}

User Preferences: {user_preferences}

Current Hierarchical Planning Structure:
{current_tree}

Available Leaf Nodes to Expand:
{leaves}

Please select the index of the leaf node that should be expanded next. Consider:
1. Which expansion would provide the most critical information for solving the query and satisfying user preferences
2. Which node represents the most urgent planning concern that affects overall solution quality
3. Which expansion would best follow the divide-and-conquer strategy by breaking complex constraints into manageable pieces
4. Which node expansion would help manage multiple sub-tasks more effectively while respecting user preferences
5. Which expansion would best contribute to systematic constraint satisfaction

Choose the index number of the leaf node to expand next. Start from 0. Return only the number, no other text."""
)


# Plan generation prompt - for generating the final travel plan using hierarchical approach
trip_plan_generation_prompt = """
You are a travel planning expert using a hierarchical thinking approach to generate detailed travel itineraries. This systematic method breaks down complex planning challenges into manageable components, handles multiple constraints simultaneously, and organizes sub-tasks effectively to create coherent travel plans in JSON format.

[Mandatory Rules]
Always reply in English. However, when using names of attractions, transportation, and hotels from the reference information, you must keep the original text and not translate them.
The output data must strictly follow the given JSON format; do not output any additional information.

[Itinerary Requirements]
1. Strictly adhere to the user's requested itinerary; do not change the travel plan (including days, cities, dates, etc.).
2. The itinerary should be in chronological order, with time periods divided into Morning/Afternoon/Evening.
3. A high-quality itinerary must include transportation, accommodation, and core attractions, all organized logically to ensure a smooth experience. Pay close attention to attraction opening hours (from the `openTimeCalendar` field) and avoid scheduling visits when they are closed.
4. Prioritize major stations for transportation arrangements, and ensure travel times strictly match the time period (e.g., a morning departure should not be scheduled in the afternoon).
5. Accommodation must be selected from the most suitable hotels in the reference data. Use only one hotel per city. Place the hotel arrangement at the end of the day's schedule. A hotel should be listed every night except for the last day of the trip.
6. Pay close attention to timing for attractions and transport to avoid conflicts that would make the itinerary impractical.
7. Ensure the itinerary's intensity is moderate. Avoid scheduling too many activities in a single time period.
8. If an attraction's `is_premium_attraction` value is 1, it requires a full day. No other attractions can be scheduled for that day.
9. You must include round-trip transportation, clearly distinguishing between the departure and return journeys.
10. Attraction choices should be seasonally appropriate for the user's travel date of 2025-08-13.
11. For short trips, focus on the city's core attractions.
12. For single-day trips, do not arrange accommodation.
13. If the user specifies a budget, strictly adhere to it. If the budget cannot be met, explain this in the `recommendReason` with the following phrasing: "No suitable options were found within your budget. We are recommending a high-value alternative for your reference."

[Reference Data Rules]
The provided data may include:
Attractions: poi (id: poiId, name: poiName)
Hotels: hotel (id: hotelid, name: hotelname)
Transportation: train/flight/bus/driving/ferry/ship (id: planid, name: trainNo/flightNo/shipName)
Hotels and transportation must be selected from the reference data. External resources may be used for attractions if they are more suitable.

[JSON Format Specification]
Accurately extract the name, type, and ID from reference data:
Attractions: type:'poi', name:poiName, id:poiId (connecting transport with the same planid should only be listed once)
Hotels: type:'hotel', name:hotelname, id:hotelid
Transportation: type:'transportation', name:trainNo/flightNo, id:planid
If an attraction is not from the reference data, set `"id": ""`, and format its name as **AttractionName** in the `description`. Transportation and hotels must be from reference data. Items with the same ID should only appear once.
The JSON format is as follows:
{
"itineraryName": "Itinerary Name (e.g., 3-Day Trip: Shanghai to Beijing)",
"recommendReason": "Reason for recommendation (under 50 words, explaining how it fits the user's needs)",
"dayInfos": [
    {
    "day": "Day number (integer, starting from 1)",
    "scheduleTitle": "Title for the day's schedule (if a full day is at one attraction, use 'Attraction Name Day Tour')",
    "scheduleDetail": [
        {
        "period": "Time period (Morning/Afternoon/Evening)",
        "description": "Elaborate on the schedule and recommendations for this period, following these rules:
                        1. Use the following Markdown format for all items: For attractions and hotels from reference data, use **[PoiName](poi_PoiId)** or **[HotelName](hotel_HotelId)** (e.g., **[Shanghai Disneyland](poi_13412802)**). For external attractions, use **AttractionName**. For transport, use only the name (e.g., **T110**). If a name is unknown, use generic phrasing like 'travel by boat' instead of mixing languages like 'take the ship'.
                        2. Attraction recommendations must be under 45 words (2-3 sentences) and contain three parts, avoiding generic filler:
                              - State the attraction's key feature (e.g., what it's known for, its cultural significance).
                              - Briefly describe the experience in relation to the user's needs (e.g., 'ride horses on the prairie', 'snorkel with tropical fish').
                              - Provide a practical tip (e.g., related to weather, photos, what to wear), but do not give time-related advice like recommended duration.
                        3. The tone must be natural and easy to understand for the user. It should be clear what to do, how to do it, and what to watch out for.
                        4. You may incorporate relevant tags, summaries, or user reviews.
                        5. For hotel recommendations, first introduce the neighborhood, then the hotel's features.",
        "detailList": [
            {
            "type": "transportation/poi/hotel",
            "id": "planid/poiId/hotelid",
            "name": "Train/Flight No./Attraction Name/Hotel Name"
            }
        ]
        }
    ]
    }
],
"tips": {
    "title": "Tips Title",
    "info": [
        "Tip 1 (Total content under 50 words)",
        "Tip 2"
        ]
    }
}
"""

# 中文 Prompts
trip_select_prompt_zh = PromptTemplate.from_template(
"""您正在使用分层思维方法来解决旅行规划问题。该方法采用树状结构，系统地将复杂问题分解为可管理的子组件。您需要选择接下来要扩展的叶节点（最具体的组件）。

查询: {query}

用户偏好: {user_preferences}

当前分层规划结构:
{current_tree}

可扩展的叶节点:
{leaves}

请选择接下来要扩展的叶节点的索引。请考虑：
1. 哪个扩展将为解决查询和满足用户偏好提供最关键的信息
2. 哪个节点代表影响整体解决方案质量的最紧迫的规划问题
3. 哪个扩展最符合分而治之的策略，将复杂的约束分解为可管理的部分
4. 哪个节点扩展将有助于在尊重用户偏好的同时更有效地管理多个子任务
5. 哪个扩展将最有助于系统地满足约束

选择接下来要扩展的叶节点的索引号，从0开始，只返回数字，不要返回任何其他的文字"""
)

trip_expand_prompt_zh = PromptTemplate.from_template(
"""您正在使用分层思维方法来解决旅行规划问题。该方法采用树状规划结构，使用分而治之的策略系统地将复杂问题分解为可管理的子组件。

查询: {query}

当前分层规划结构:
{current_tree}

选定要扩展的节点: {selected_node}

用户偏好: {user_preferences}

请将此节点扩展为其相关的子组件。请考虑：
1. 此规划组件的哪些关键子方面需要单独处理约束？
2. 如何使用分而治之的策略将其分解，以同时管理多个用户偏好？
3. 哪些具体的约束、要求或用户偏好适用于此组件？
4. 如何将每个子组件视为独立的子任务，同时确保整体一致性？
5. 此组件与用户偏好之间存在哪些依赖关系？

以以下格式提供扩展的子组件列表：[组件1][组件2][组件3]"""
)

trip_execute_prompt_zh = PromptTemplate.from_template(
"""您正在使用分层思维方法为旅行安排生成全面的规划流程。这种系统方法使用树状解决方案结构，通过分而治之的策略分解复杂的规划挑战，同时管理多个约束和用户偏好。

可用信息:
{given_information}

查询: {query}

用户偏好: {user_preferences}

解决方案策略（分层规划结构）:
{solution_strategy}

基于上述分层解决方案策略，请生成一个详细的思考过程，该过程：

1.  **系统地分析**策略树中的**每个组件**，有条不紊地处理分支
2.  为每个方面**识别和管理约束**，包括将用户偏好作为约束因素
3.  在处理相互依赖关系的同时，为交通、住宿和景点**做出具体决策**
4.  **确保**所有规划元素和子任务之间的**一致性和连贯性**
5.  通过全面的约束检查**验证**整个计划的**可行性**
6.  **应用分而治之的原则**，高效地处理复杂的多方面需求
7.  **严格遵守信息**：每个酒店、景点和交通选项**必须**从“可用信息”中明确列出的项目中**独家选择**。不允许捏造或使用外部选项。

系统地思考策略树的每个分支。对于每个节点，说明它如何与层次结构中的父节点和兄弟节点相关联。提供详细的推理，以显示分层约束管理。将预算限制、时间限制、用户偏好和实际考虑作为相互关联的约束因素来处理，而不是孤立的需求。

您的思考过程应展示分层方法如何有效地组织和管理旅行规划的复杂性，同时满足多个同步约束。"""
)

trip_plan_generation_prompt_zh = """
你是一位专业的旅行规划师，运用分层思维方法，生成详尽的旅行计划。通过这种系统化的方法，你将复杂的规划问题分解成易于管理的部分，同时处理多个约束条件，并有效地组织各项子任务，以JSON格式创建出条理清晰的旅行计划。

【必须遵守】
始终使用中文回复，不得使用英文或其他语言。但如果使用了参考信息中的景点名、交通和酒店名，请保持参考信息中的原文，不要翻译。
输出数据必须严格遵循给定的JSON格式，不要输出其他额外信息

【行程安排要求】
1.严格按用户要求安排行程，不得更改用户的旅行计划（包括天数、旅行城市、旅行日期等）
2.行程按时间顺序排列，时段划分为上午/下午/晚上
3.优质行程应包含交通安排、住宿和核心景点，所有项目按合理时间顺序组织以确保流畅体验，尤其注意景点营业时间(openTimeCalendar字段)限制，避免将景点安排在不营业或停止入园的时段。
4.交通安排优先选择主要站点，特别注意交通时间必须严格对应时段（避免将早晨出发安排在下午/晚间时段）
5.住宿需从参考数据中选择最合适的酒店，同一城市无需更换酒店，仅安排一家酒店即可，酒店安排置于当日末尾，每天晚上尽量指明酒店安排，但旅程最后一天晚上无需安排酒店
6.特别注意景点和交通的时间要求，避免时间冲突导致行程不合理或无法实现。
7.确保行程强度和体力消耗适中，同一时段避免安排过多活动。
8.若景点的is_premium_attraction值为1，表示该景点需全天游览，当日不可安排其他景点。
9.必须包含往返交通安排，注意区分去程和返程行程。
10.景点安排需符合季节特性，用户出游日期为2025-08-13。
11.若用户游玩天数较短，建议集中游览城市内的核心景点
12. 如果用户是一日游，则不需要安排酒店。
13. 如果用户对行程预算有要求，请在行程安排时严格满足用户的预算需求，尽量不要超出用户的预算范围，但是当线路安排无法满足用户的预算时，请在推荐理由中补充说明，话术如：“您的预算范围内未找到合适方案，为您推荐高性价比方案作为参考”

【参考数据规则】
提供的数据可能包含：
景点：poi（id: poiId, name: poiName）
酒店：hotel（id: hotelid, name: hotelname）
交通：火车/航班/巴士/自驾/渡轮/轮船（id: planid, 名称: trainNo/flightNo/shipName）
酒店和交通必须从参考数据中选择，景点则允许使用外部资源（若更合适）。

【JSON格式规范】
使用参考数据时精确提取名称、类型和ID：
景点：type:'poi', name:poiName, id:poiId（相同planid的接驳交通仅需输出一次）
酒店：type:'hotel', name:hotelname, id:hotelid
交通：type:'transportation', name:trainNo/flightNo, id:planid
如果景点不在参考数据中，需设置"id": ""，同时在description中提及该景点时，格式使用**景点名称**，无需其他辅助说明，交通和酒店必须来自参考数据，相同ID的项目仅输出一次，避免重复。
JSON格式如下：
{
"itineraryName": "行程名称（例：3日旅行行程：上海至北京）",
"recommendReason": "推荐理由（50字内，说明行程契合用户需求）",
"dayInfos": [
    {
    "day": "天数序号（从1开始的整数）",
    "scheduleTitle": "当日行程标题，如果安排全天都玩某个景点，标题建议直接采用xxx一日游",
    "scheduleDetail": [
        {
        "period": "时段（上午/下午/晚上）",
        "description": "阐述该时段内的行程安排以及推荐理由，具体需满足：
                        1. 需按以下markdown格式提及所有要经历景点/酒店/交通：对于景点及酒店，你需要提取具体名字及id，格式遵循**[PoiName](poi_PoiId)** 或 **[HotelName](hotel_HotelId)**，如**[上海迪士尼度假区](poi_13412802)**, **[上海和平饭店](hotel_20987296)**，但是若景点不在参考数据中时，格式遵循**PoiName**。对于交通仅需要提取交通名称，如**T110**，特别注意：当你不知道具体名字时，就不要提及具体名称，更不要把id填在名字处，可以根据tripType的类型，用乘船、坐车等话术描述，但不要说乘坐ship类似这种中英文夹杂的话说。
                        2. 景点推荐理由包含以下三部分内容，字数在45个字以内，总长度控制在两到三句话内，应避免一切无信息量修辞，如“相映成趣”“风光壮阔”“山水如画”等：
                              - 明确点出该景点的认知锚点（如上榜理由、地形特征或文化属性）；
                              - 结合用户需求，简洁说明玩法/体验，要具体、可感知，例如“骑马看草原”“水下浮潜看热带鱼”等；
                              - 结合用户需求，给出一句实用贴士，如时间、天气、防晒、拍照角度、出行方式等（避免推销感，只提供客观选择），但不要给和时间相关的建议，比如不要给建议游玩时长，建议晚上游玩等建议；
                        3. 推荐理由语言要求自然顺畅，不要堆概念或使用拗口术语，要用用户语言；要让用户一看就知道这个地方是干嘛的、怎么玩、需注意什么，具有实际参考价值；
                        4. 如有优质景点标签、简介、用户评价，可融合在推荐理由中。
                        5. 酒店推荐理由，注意要先介绍酒店所属的住宿区域，再介绍酒店自身特点",
        "detailList": [
            {
            "type": "transportation/poi/hotel",
            "id": "planid/poiId/hotelid",
            "name": "车次/航班号/景点名/酒店名"
            }
        ]
        }
    ]
    }
],
"tips": {
    "title": "提示标题",
    "info": [
        "提示内容1 (总内容限定在50字内)",
        "提示内容2"
        ]
    }
}
"""