import json
import os
import sys
from typing import Any, Dict, List, Tuple
import copy
from requests import api
# from utils.time_utils import _time_period_strict
from utils.poi_analyzer import POIAnalyzer


# Add project root to path
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
if CURRENT_DIR not in sys.path:
	sys.path.append(CURRENT_DIR)

from utils.prompt_template import (
	ItineraryGenTrafficUsrZh,
	ItineraryGenTrafficUsrEn,
	ItineraryGenTrafficSysZh,
	ItineraryGenTrafficSysZhOutside,
	ItineraryGenTrafficSysEn,
	ItineraryGenTrafficSysEnOutside,
)


def _safe_json_load(maybe_json: Any) -> Any:
	if isinstance(maybe_json, str):
		try:
			return json.loads(maybe_json)
		except Exception:
			return maybe_json
	return maybe_json

def _choose_templates(locale: str, has_transport: bool) -> Tuple[str, str]:
	is_zh = (locale or '').lower().startswith('zh')
	if is_zh:
		sys_tpl = ItineraryGenTrafficSysZh if has_transport else ItineraryGenTrafficSysZhOutside
		usr_tpl = ItineraryGenTrafficUsrZh
	else:
		sys_tpl = ItineraryGenTrafficSysEn if has_transport else ItineraryGenTrafficSysEnOutside
		usr_tpl = ItineraryGenTrafficUsrEn
	return sys_tpl, usr_tpl


def _extract_first_system(messages: List[Dict[str, Any]]) -> str:
	for msg in messages:
		if (msg.get('role') or '').lower() == 'system':
			return msg.get('content', '')
	return ''


def _extract_last_user(messages: List[Dict[str, Any]]) -> str:
	for msg in reversed(messages):
		if (msg.get('role') or '').lower() == 'user':
			return msg.get('content', '')
	return ''


def _build_message_from_reference(poi_dict: Dict[str, Any]) -> str:
    """
    Build a temporary prompt using existing reference info if available; otherwise
    fallback to formatting with current resources. Returns a single user prompt string.
    """
    locale = poi_dict.get('locale', 'en-US')
    user_query = poi_dict.get('userQuery', '')
    ref_text = poi_dict.get('reference', '')

    if ref_text:
        ref_text = ref_text.replace("[References]", "").strip()

    # Fallback: use existing resource-based formatting
    sys_tpl, _ = _choose_templates(locale, True)
    system_message = sys_tpl % ('用户出游日期未知' if locale.lower().startswith('zh') else 'unknown travel date')
    if locale.lower().startswith('zh'):
        user_message = "[参考信息]\n" + ref_text + "\n\n[用户需求]\n" + user_query
    else:
        user_message = "[References]\n" + ref_text + "\n\n[User Query]\n" + user_query

    return  {
        'messages': [
            {'role': 'system', 'content': system_message},
            {'role': 'user', 'content': user_message},
        ],
        'case_index': 0,
        'locale': locale,
    }


def _build_refinement_messages(poi_dict: Dict[str, Any], raw_itinerary_str: str, current_itinerary: Dict[str, Any], evaluation_results: Dict[str, Any]) -> List[Dict[str, str]]:
    """
    Build refinement prompt messages from poi_dict, current_itinerary, and evaluation_results.
    Returns a list of message dictionaries for system and user roles.
    """
    locale = poi_dict.get('locale', 'en-US')

    # Choose appropriate system template based on locale
    if locale.lower().startswith('zh'):
        from utils.prompt_template import ItineraryGenerationReviewSysZh
        system_message = ItineraryGenerationReviewSysZh
    else:
        from utils.prompt_template import ItineraryGenerationReviewSysEn
        system_message = ItineraryGenerationReviewSysEn

    # Extract evaluation details (JSON objects)
    format_details = evaluation_results.get('format_details', {}).get("validation_results", {})
    commonsense_details = evaluation_results.get('commonsense_details', {}).get("violations", {})
    soft_constraint_details = evaluation_results.get('soft_constraint_details', {}).get("violations", {})
    preference_details = evaluation_results.get('preference_details', {}).get("user_preferences", {})
    user_request_details = evaluation_results.get('user_request_details', {}).get("detailed_feedback", {})

    # Convert JSON details to formatted strings
    format_details_str = json.dumps(format_details, ensure_ascii=False, indent=2) if format_details else "无问题"
    commonsense_details_str = json.dumps(commonsense_details, ensure_ascii=False, indent=2) if commonsense_details else "无问题"
    soft_constraint_details_str = json.dumps(soft_constraint_details, ensure_ascii=False, indent=2) if soft_constraint_details else "无问题"
    preference_details_str = json.dumps(preference_details, ensure_ascii=False, indent=2) if preference_details else "无问题"
    user_request_details_str = json.dumps(user_request_details, ensure_ascii=False, indent=2) if user_request_details else "无问题"

    # Format the current itinerary for display
    if current_itinerary:
        current_itinerary_str = json.dumps(current_itinerary, ensure_ascii=False, indent=2)
    else:
        if raw_itinerary_str:
            current_itinerary_str = raw_itinerary_str
        else:
            current_itinerary_str = "invalid itinerary"

    # Build reference information with detailed context
    reference_info = poi_dict.get('reference', '')

    # Add additional context from poi_dict if available
    additional_context = []
    if 'hotel_pool' in poi_dict:
        additional_context.append(f"Available Hotels: {poi_dict['hotel_pool']}")
    if 'poi_pool' in poi_dict:
        additional_context.append(f"Available POIs: {poi_dict['poi_pool']}")
    if 'transport_pool' in poi_dict:
        additional_context.append(f"Available Transportation: {poi_dict['transport_pool']}")

    if additional_context:
        reference_info += "\n\n" + "\n".join(additional_context)

    # Build user message with feedback
    if locale.lower().startswith('zh'):
        user_message = f"""
[评估反馈]
格式问题: {format_details_str}
常识问题: {commonsense_details_str}
软约束问题: {soft_constraint_details_str}
偏好问题: {preference_details_str}
用户需求问题: {user_request_details_str}

[原始查询]
{poi_dict.get('userQuery', '')}

[参考信息]
{reference_info}

[需要优化的行程]
请根据上述评估反馈，优化以下行程：
{current_itinerary_str}
"""
    else:
        user_message = f"""
[Evaluation Feedback]
Format Issues: {format_details_str}
Commonsense Issues: {commonsense_details_str}
Soft Constraint Issues: {soft_constraint_details_str}
Preference Issues: {preference_details_str}
User Request Issues: {user_request_details_str}

[Original Query]
{poi_dict.get('userQuery', '')}

[Reference Information]
{reference_info}

[Itinerary to Optimize]
Please optimize the following itinerary based on the evaluation feedback above:
{current_itinerary_str}
"""

    return [
        {'role': 'system', 'content': system_message},
        {'role': 'user', 'content': user_message.strip()}
    ]
