<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\CampaignApprovalBinding;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Approvals\Approval;
use Laravel\Ai\Concerns\InteractsWithApprovals;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;
use Throwable;

/**
 * Copy an ad group or an ad that is already on Google.
 *
 * duplicate_campaign copies a whole campaign into a new local draft and sends
 * nothing to a platform, which is the right thing for starting again from a
 * campaign that worked. It is not what a buyer means by "make another one like
 * that ad group": they want a second ad group beside the first, on the campaign
 * already running, keeping the keywords they settled on.
 *
 * Nothing smaller than a campaign could be copied on any platform before this.
 *
 * Google has no copy operation, so this reads the source and creates from it.
 * Everything lands PAUSED. Approval is always asked, the same as add_ads, which
 * also creates paused objects on a live account: paused costs nothing today,
 * but it is still something real appearing on an account somebody is spending
 * on, and the buyer should know it is there.
 */
class CopyEntity implements Approvable, Tool
{
    use ActsOnFocusedCampaign, InteractsWithApprovals;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly CampaignApprovalBinding $approvalBinding,
    ) {}

    public function description(): Stringable|string
    {
        return 'Copy an ad group or an ad that is already live on Google - duplicate it, clone it, '
            .'make another one like it. An ad group copy brings its keywords and their match types, '
            .'and its ads unless told otherwise. Everything is created paused, so nothing starts '
            .'spending until it is started. Needs the id from list_campaign_structure. The user '
            .'approves it. To copy a whole campaign into a fresh draft instead, use '
            .'duplicate_campaign, which touches no platform.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'entity_type' => $schema->string()->enum(['ad_group', 'ad_set', 'ad'])
                ->description('Which level to copy. ad_set is Meta\'s word for an ad group and is '
                    .'accepted for it.')
                ->required(),
            'id' => $schema->string()
                ->description('The platform id to copy, from list_campaign_structure.')
                ->required(),
            'name' => $schema->string()
                ->description('Ad group only. A name for the copy. Defaults to the original followed '
                    .'by "(copy)".'),
            'ad_group_id' => $schema->string()
                ->description('Ad only. Put the copy in this ad group instead of the one the original '
                    .'sits in.'),
            'include_ads' => $schema->boolean()
                ->description('Ad group only. Copy its ads as well. True unless told otherwise.'),
        ];
    }

    /** Always. This puts something new on a live account. */
    protected function needsApproval(Request $request): Approval|bool
    {
        return $this->approvalBinding->request($request, $this->focused(), 'copy_entity');
    }

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

        $arguments = $request->all();
        $type = (string) ($arguments['entity_type'] ?? '');
        $type = $type === 'ad_set' ? 'ad_group' : $type;
        $id = trim((string) ($arguments['id'] ?? ''));

        if (! in_array($type, ['ad_group', 'ad'], true) || $id === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Say whether to copy an ad_group or an ad, and give its id from list_campaign_structure.',
            ]);
        }

        if ($campaign->platform !== 'google') {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    'Copying a single ad group or ad is only available on Google. This campaign is on %s.',
                    ucfirst((string) $campaign->platform),
                ),
                'note' => 'duplicate_campaign copies a whole campaign into a new draft on any platform. Offer that instead.',
            ]);
        }

        if (! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'This campaign has not been published, so there is nothing on Google to copy.',
                'note' => 'Its ad groups and ads do not exist yet. Do not describe this as a failure.',
            ]);
        }

        $connection = GoogleAdsConnection::shared();

        if ($connection === null) {
            return $this->json([
                'ok' => false,
                'error' => ucfirst(GoogleAdsConnection::missingReason()).'.',
                'note' => 'Nothing was copied. This needs an administrator.',
            ]);
        }

        // The account the campaign is on, not the configured default. See
        // GoogleAdsConnection::onCustomer - the allow list still gates it.
        $connection = $connection->onCustomer($campaign->ad_account_id);

        $google = app(GoogleAdsService::class);

        // Checked against the campaign's own structure before anything is
        // created, for the reason the other entity tools do it: the allow list
        // governs the account, not the objects inside it, so an id carried over
        // from an earlier turn would otherwise copy a stranger's ad group into
        // this buyer's campaign.
        try {
            $structure = $google->readCampaignStructure($connection, (string) $campaign->external_campaign_id);
        } catch (Throwable $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'The platform could not be read, so nothing was copied. Do not retry blindly.',
            ]);
        }

        $known = array_column($type === 'ad_group' ? $structure['ad_groups'] : $structure['ads'], 'id');

        if (! in_array($id, $known, true)) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    '%s %s is not in this campaign, so nothing was copied.',
                    $type === 'ad_group' ? 'Ad group' : 'Ad',
                    $id,
                ),
                'note' => 'Call list_campaign_structure for the current ids. Do not try this one again.',
            ]);
        }

        return $type === 'ad_group'
            ? $this->copyAdGroup($campaign, $google, $connection, $id, $arguments)
            : $this->copyAd($campaign, $google, $connection, $id, $structure, $arguments);
    }

    /** @param array<string, mixed> $arguments */
    private function copyAdGroup(
        Campaign $campaign,
        GoogleAdsService $google,
        GoogleAdsConnection $connection,
        string $id,
        array $arguments,
    ): Stringable|string {
        $withAds = ! array_key_exists('include_ads', $arguments) || (bool) $arguments['include_ads'];

        try {
            $copy = $google->duplicateAdGroup(
                $connection,
                $id,
                filled($arguments['name'] ?? null) ? (string) $arguments['name'] : null,
                $withAds,
            );
        } catch (Throwable $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'Say what the message says about what is on the account. Do not describe this as done.',
            ]);
        }

        return $this->json([
            'ok' => true,
            'entity_type' => 'ad_group',
            'copied_from' => $id,
            'ad_group_id' => $copy['ad_group_id'],
            'keywords' => $copy['keywords'],
            'ads' => $copy['ads'],
            'note' => sprintf(
                'A copy of the ad group is on the campaign, paused, with %d keyword(s) and %d ad(s). '
                    .'Say its new id and that it is not delivering until it is started with '
                    .'set_entity_status. It is a copy of what is live now, not of what the campaign '
                    .'was built from, so say that if they expected the original draft copy.',
                $copy['keywords'],
                count($copy['ads']),
            ),
        ]);
    }

    /**
     * @param  array{ad_groups: list<array<string, mixed>>, ads: list<array<string, mixed>>, asset_groups: list<array<string, mixed>>}  $structure
     * @param  array<string, mixed>  $arguments
     */
    private function copyAd(
        Campaign $campaign,
        GoogleAdsService $google,
        GoogleAdsConnection $connection,
        string $id,
        array $structure,
        array $arguments,
    ): Stringable|string {
        $target = trim((string) ($arguments['ad_group_id'] ?? ''));

        // A named destination has to be one of this campaign's own ad groups.
        // Without this an ad could be copied into any ad group on the account,
        // including one belonging to a campaign nobody in this chat opened.
        if ($target !== '' && ! in_array($target, array_column($structure['ad_groups'], 'id'), true)) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Ad group %s is not in this campaign, so nothing was copied.', $target),
                'note' => 'Call list_campaign_structure for the current ids.',
            ]);
        }

        try {
            $newId = $google->duplicateAd($connection, $id, $target ?: null);
        } catch (Throwable $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'Say what the message says about what is on the account. Do not describe this as done.',
            ]);
        }

        return $this->json([
            'ok' => true,
            'entity_type' => 'ad',
            'copied_from' => $id,
            'ad_id' => $newId,
            'ad_group_id' => $target ?: null,
            'note' => 'A copy of the ad is in place, paused. Say its new id and that it is not '
                .'delivering until it is started with set_entity_status.',
        ]);
    }
}
