import os
import json
from openai import OpenAI
# ツールのソースコードをインポート
from weather_tool import weather_tool, WEATHER_TOOL
from duckduckgo_search_tool import duckduckgo_search_tool, DUCKDUCKGO_TOOL

# ツールの名前と関数の名前のマッピング
TOOL_FUNCTIONS = {
  "duckduckgo_search": duckduckgo_search_tool,
  "get_weather": weather_tool,
}

def create_openai_client():
  """OpenAIクライアントを初期化"""
  return OpenAI(
    base_url="http://localhost:11434/v1",
    api_key="dummy"
  )

# プロンプトテンプレート
PROMPT_TEMPLATE = """
{destination}の{duration_days}日間観光プランを作成してください。

手順：
1. get_weather で天気取得(get_weatherに与える地名はローマ字にすること）
2. 「{destination}のベスト観光スポット10」を検索
3. 得られた天気・観光情報を元にした旅行プランを作成する

注意:
- 検索結果から得た地名以外の場所は、旅行プランに含めないこと。
- 検索は1回のみ実行すること。追加の検索は不要。
- 1回の検索結果で十分な旅行プランを作成すること。

旅行プランの内容：
- タイトル:{destination} {duration_days}日間プラン 
  with 天候情報（気温・湿度・風速の実数値を記載）
- スケジュールと観光スポット
- 天気によって観光スポット選定を考慮した点
"""

def create_travel_plan(destination: str, duration_days: int = 1) -> str:
  """指定された目的地と期間の旅行プランを作成"""
  client = create_openai_client()

  # （1）メッセージ履歴リスト（messages）を初期化
  messages = [
    {"role": "user", "content": PROMPT_TEMPLATE.format(
      destination=destination, duration_days=duration_days)}
  ]

  # 最大ループ回数を設定
  max_iterations = 10
  iteration = 0

  # （2）LLM呼び出しと履歴送信のループ
  while iteration < max_iterations:
    # LLMに推論を依頼
    response = client.chat.completions.create(
      model="gpt-oss:20b",
      messages=messages,
      tools=[WEATHER_TOOL, DUCKDUCKGO_TOOL],   # ツールのデータを渡す
    )

    message = response.choices[0].message
    # （3）ツール使用の要求あり？
    if hasattr(message, 'tool_calls') and message.tool_calls:
      # アシスタント（LLM）の応答を追加
      messages.append({
        "role": "assistant",
        "content": message.content,
        "tool_calls": [{   
          "id": tc.id,
          "type": "function",
          "function": {
            "name": tc.function.name,
            "arguments": tc.function.arguments
          }
        } for tc in message.tool_calls]
      })

      # （4）各ツールを実行 
      for tool_call in message.tool_calls:
        function_name = tool_call.function.name
        arguments = json.loads(tool_call.function.arguments or "{}")

        # ツールを実行して結果を取得
        result = TOOL_FUNCTIONS[function_name](**arguments)

        # （5）ツールの実行結果をmessagesに追加
        messages.append({
          "tool_call_id": tool_call.id,
          "role": "tool",
          "name": function_name,
          "content": str(result)
        })
      iteration += 1
    else:
      # ツール使用の要求がなかった場合
      if message.content:
        # アシスタント（LLM）の応答（最終的な回答）を追加
        messages.append({"role": "assistant", "content": message.content})
      # ループを終了
      break
  # （6）アシスタント（LLM）の応答のみを抽出して返す
  return "\n\n".join([msg["content"] for msg in messages
                     if msg.get("role") == "assistant" and msg.get("content")])

if __name__ == "__main__":
  import sys
  if len(sys.argv) != 2:
    print("使用方法: python travel_agent.py <目的地>")
    sys.exit(1)
  destination = sys.argv[1]
  print(create_travel_plan(destination))