<?php

namespace App\Synapse\Tools;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

class WebSearchTool implements Tool
{
    public function description(): Stringable|string
    {
        return 'Search the internet for information about an institution, organisation, or topic. Use this to find current contact details, DSAR/SAR routes, whether an institution still exists, its successor authority, archived historical records, and any publicly available information relevant to the DSAR strategy. Prefer specific queries such as institution name + location + "subject access request" or "data protection officer".';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'query' => $schema->string()
                ->description('The search query. Be specific — include institution name, location, and what you are looking for (e.g. "Highland Council data protection officer SAR contact", "Rosedene Inverness children\'s home history records").')
                ->required(),
        ];
    }

    public function handle(Request $request): Stringable|string
    {
        $query = trim($request['query'] ?? '');

        if ($query === '') {
            return json_encode(['error' => 'query is required']);
        }

        $apiKey = config('services.tavily.api_key');

        if (!$apiKey) {
            return json_encode(['error' => 'Web search is not configured (TAVILY_API_KEY missing).']);
        }

        $response = Http::timeout(30)
            ->post('https://api.tavily.com/search', [
                'api_key'      => $apiKey,
                'query'        => $query,
                'search_depth' => 'advanced',
                'max_results'  => 5,
                'include_answer' => true,
            ]);

        if ($response->failed()) {
            return json_encode(['error' => 'Web search request failed: ' . $response->status()]);
        }

        $data = $response->json();

        $results = collect($data['results'] ?? [])->map(fn ($r) => [
            'title'   => $r['title'] ?? '',
            'url'     => $r['url'] ?? '',
            'content' => $r['content'] ?? '',
        ])->values()->all();

        return json_encode([
            'query'   => $query,
            'answer'  => $data['answer'] ?? null,
            'results' => $results,
        ]);
    }
}
