<?php

namespace App\Mcp\Tools\GoogleAds;

use App\Services\LandingPageAnalyzer;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
use Throwable;

/**
 * The Google MCP server's view of the shared landing page analyser.
 *
 * Reading the page is not a Google concern: the same page decides the Meta
 * objective and the ad copy for both platforms. The work lives in
 * {@see LandingPageAnalyzer} and this is the MCP-shaped door to it, so the
 * agent tool and the MCP server cannot drift apart.
 */
#[Description('Read a public landing page URL and suggest campaign fields from its content. Use this before account and campaign setup when the user provides a URL. Never invent details that are not present on the page.')]
class AnalyzeLandingPage extends Tool
{
    public function __construct(private readonly LandingPageAnalyzer $analyzer) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'url' => $schema->string()->description('Public landing page URL')->required(),
        ];
    }

    public function handle(Request $request): Response
    {
        if ($request->user() === null) {
            return Response::error('Authentication is required.');
        }

        $data = $request->validate([
            'url' => ['required', 'url:http,https', 'max:2048'],
        ]);

        try {
            $analysis = $this->analyzer->analyze($data['url']);
        } catch (Throwable $exception) {
            return Response::error($exception->getMessage());
        }

        return Response::json([
            'ok' => true,
            ...$analysis->toArray(),
            'next' => 'Show these suggestions to the user one field at a time and ask for confirmation or edits before continuing.',
        ]);
    }
}
