<?php
// app/api/tools_demo.php - Demonstrate Responses API tool calling (function calling) once
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/openai_client.php';

header('Content-Type: application/json');

$question = isset($_POST['question']) ? $_POST['question'] : 'Cuaca di Jakarta hari ini?';

// Define a simple tool schema: get_time and get_weather (mocked)
$tools = [
    [
        'type' => 'function',
        'function' => [
            'name' => 'get_time',
            'description' => 'Get current server time in Asia/Jakarta',
            'parameters' => [
                'type' => 'object',
                'properties' => []
            ]
        ]
    ],
    [
        'type' => 'function',
        'function' => [
            'name' => 'get_weather',
            'description' => 'Get fake weather for a city (demo only)',
            'parameters' => [
                'type' => 'object',
                'properties' => [
                    'city' => ['type' => 'string']
                ],
                'required' => ['city']
            ]
        ]
    ]
];

$body = [
    'model' => openai_model(),
    'tools' => $tools,
    'input' => [
        ['role' => 'user', 'content' => [
            ['type' => 'input_text', 'text' => $question]
        ]]
    ]
];

$resp = openai_create($body);

// If the model requested a tool call, simulate it
$tool_calls = [];
if (isset($resp['output'])) {
    foreach ($resp['output'] as $item) {
        if (isset($item['type']) && $item['type'] === 'tool_call') {
            $tool_calls[] = $item;
        }
    }
}

$followup = null;
if (!empty($tool_calls)) {
    $tool_results = [];
    foreach ($tool_calls as $tc) {
        $name = $tc['name'];
        $args = isset($tc['arguments']) ? $tc['arguments'] : [];
        if ($name === 'get_time') {
            date_default_timezone_set('Asia/Jakarta');
            $tool_results[] = [
                'type' => 'tool_result',
                'tool_call_id' => $tc['id'],
                'content' => [['type' => 'output_text', 'text' => date('c')]]
            ];
        } elseif ($name === 'get_weather') {
            $city = isset($args['city']) ? $args['city'] : 'Jakarta';
            $tool_results[] = [
                'type' => 'tool_result',
                'tool_call_id' => $tc['id'],
                'content' => [['type' => 'output_text', 'text' => "Cuaca (demo) $city: cerah 31°C"]]
            ];
        }
    }
    // Send follow-up with tool results (previous_response_id)
    $followup = openai_create([
        'model' => openai_model(),
        'input' => $tool_results,
        'previous_response_id' => $resp['id']
    ]);
}

echo json_encode(['initial' => $resp, 'followup' => $followup]);
