<?php

namespace App\Agent\Tools\Campaign;

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

/**
 * Ask for the campaign in focus to be published.
 *
 * This is a request, not an act. It records what would be created and returns
 * the summary for the user to approve; nothing reaches a platform until a human
 * approves separately. The agent has no tool that publishes.
 */
class RequestPublish implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly PublishGate $gate,
    ) {}

    public function description(): Stringable|string
    {
        return 'Check whether the campaign in focus is ready and ask the user to approve it. '
            .'Call this when nothing is blocking. You cannot publish; only the user can.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [];
    }

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

        if ($blocking = $this->gate->check($campaign)) {
            return $this->json([
                'ok' => false,
                'ready' => false,
                'still_needed' => $blocking,
            ]);
        }

        return $this->json([
            'ok' => true,
            'ready' => true,
            'summary' => [
                'campaign' => $campaign->name,
                'objective' => $campaign->objective,
                'landing_url' => $campaign->landing_url,
                'daily_budget' => $campaign->budget,
                'currency' => $campaign->currency,
                'bidding' => $campaign->bid_strategy,
                'target_cost' => $campaign->bid_amount,
                'countries' => $campaign->locations['countries'] ?? [],
                'placements' => $campaign->placements,
                'ad_account_id' => $campaign->ad_account_id,
                'page_id' => $campaign->page_id,
                'pixel_id' => $campaign->pixel_id,
                'ads' => $campaign->ads()->count(),
            ],
            'note' => 'Show the user this summary, including the ad account, Page and pixel ids, '
                .'and ask them to approve. Everything is created paused.',
        ]);
    }
}
