import ollama
import sys 
from datetime import datetime, timezone
import random
from rich import print

# 現在時刻を取得する関数
def get_time():
  return datetime.now(timezone.utc).astimezone().isoformat()

# 現在の道路の状況を取得する関数
def get_road_conditions(road: str) -> str:
  # 本来ならネットから現在の道路の状況を取得するが、
  # ここでは適当な状況を返す
  conditions = ['very congested', 
                'congested', 
                'a little congested', 
                'clear', 
                'closed']
  temp = random.choice(conditions)
  return f'The {road} road is {temp}.'

available_tools = {'get_time': get_time, 
                   'get_road_conditions': get_road_conditions}

# コマンドライン引数でプロンプトを記述
# 引数がない場合のデフォルトのプロンプト
question = "現在時刻を教えてください。東名高速道路の状況は？" 

if len(sys.argv) > 1:
  question = sys.argv[1]

messages = [{"role": "user", 
             "content": f"{question}日本語で答えてください。" + 
                        "「お答えします：」で始めてください。"}]

client = ollama.Client(host="localhost:11434")

while True:
  response = client.chat(model="gpt-oss:20b", 
                         messages=messages, 
                         tools=[get_time, 
                                get_road_conditions])
                                
  if response.message.content:
    print('回答: ')
    print(response.message.content + '\n')
  #if response.message.thinking:              # （A）
  #  print('Thinking: ')                      # （A）
  #  print(response.message.thinking + '\n')  # （A）

  messages.append(response.message)

  if response.message.tool_calls:
    for tool_call in response.message.tool_calls:
      function_to_call = available_tools.get(tool_call.function.name)
      if function_to_call:
        result = function_to_call(**tool_call.function.arguments)
        print('Result from tool call name: ', 
              tool_call.function.name, 'with arguments: ', 
          tool_call.function.arguments, 'result: ', result + '\n')
        messages.append({'role': 'tool', 
                         'content': result, 
                         'tool_name': tool_call.function.name})
      else:
        print(f'Tool {tool_call.function.name} not found')
  else:
    break
