<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Targeting\AudienceSizing;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

class ReviewAudienceSizing implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly AudienceSizing $sizing,
    ) {}

    public function description(): Stringable|string
    {
        return 'Show available audience-size evidence for the campaign in focus. '
            .'Google Search, Meta website audiences, and LinkedIn retargeting segments can show provider-reported per-list sizes when available. '
            .'Do not call these figures total campaign reach or a forecast.';
    }

    public function handle(Request $request): Stringable|string
    {
        if (! $campaign = $this->focused()) {
            return $this->noCampaign();
        }

        return $this->json(['ok' => true, 'estimate' => $this->sizing->review($campaign, ($request->all()['refresh'] ?? false) === true)]);
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'refresh' => $schema->boolean()->description('Request new provider list sizes when the cached result is stale.'),
        ];
    }
}
