<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\CampaignApprovalBinding;
use App\Campaigns\LinkedInManagement;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Support\Actor;
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;

/**
 * Remove a campaign, an ad set or an ad from Meta for good.
 *
 * The only irreversible thing this product can do. Meta's own refusal, verbatim:
 * "This campaign has been deleted, so it can't be restored and only its name can
 * be changed. To use these settings again, duplicate the campaign and edit the
 * copy." There is no undo to offer afterwards, so everything worth checking has
 * to be checked before.
 *
 * Three guards, each from something that actually went wrong.
 *
 * Delivery first. On 9 Oct a campaign holding 346.61 USD of spend and 66,652
 * impressions, still delivering, was deleted during a cleanup of test
 * campaigns. Every other campaign in that sweep had zero spend and zero
 * impressions, so a single read would have separated them. Anything that has
 * ever delivered is refused, with the numbers, until somebody says again that
 * they mean it.
 *
 * Ownership second. The account allow list governs which account may be written
 * to, not which object inside it, so an id the model carried over from an
 * earlier turn would otherwise delete a stranger's ad set on a permitted
 * account.
 *
 * And the local record last, only once the platform has confirmed. The same
 * cleanup cleared local ids on the strength of a rollback that reported success
 * having done nothing, which left five live Google campaigns with no record
 * here at all - the exact orphan the ids exist to prevent.
 *
 * Always approval-gated, unlike pausing. Pausing stops money; this destroys
 * work.
 */
class DeleteEntity implements Approvable, Tool
{
    use ActsOnFocusedCampaign, InteractsWithApprovals;

    /** Most objects one call may remove, so a mistake is bounded. */
    private const MOST_PER_CALL = 10;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Meta $meta,
        private readonly Actor $actor,
        private readonly CampaignApprovalBinding $approvalBinding,
    ) {}

    public function description(): Stringable|string
    {
        return 'Delete a Meta or Google campaign/ad set/ad group/ad, or a LinkedIn '
            .'campaign/campaign_group/creative/ad after approval. LinkedIn draft deletion is '
            .'immediate; other states request pending deletion and keep IDs until confirmed. '
            .'LinkedIn parents with children are refused; remove children separately. Remove, get '
            .'rid of, take it down. This cannot be undone: no platform here restores a deleted '
            .'object. Needs ids from '
            .'list_campaign_structure, except when deleting the campaign in focus itself. Anything '
            .'that has ever delivered is refused until the user confirms a second time, and the user '
            .'always has to approve. Prefer set_entity_status with PAUSED if they only want it to '
            .'stop - a paused object can be restarted, a deleted one cannot.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'entity_type' => $schema->string()->enum(['campaign', 'ad_set', 'ad_group', 'ad', 'creative', 'campaign_group'])
                ->description('Which level to delete. ad_set is Meta\'s word and ad_group is Google\'s; '
                    .'either is accepted for that level. creative and campaign_group are LinkedIn\'s.')
                ->required(),
            'ids' => $schema->array()->items($schema->string())
                ->description('Platform ids to delete. Omit for entity_type=campaign to delete the campaign in focus.'),
            'delete_even_though_it_delivered' => $schema->boolean()
                ->description('Only set this after telling the user how much the object spent and how '
                    .'many impressions it had, and after they have confirmed they still want it gone. '
                    .'Never set it on the first attempt.'),
        ];
    }

    /** Always. There is no undo, so this is never done on the model's say-so. */
    protected function needsApproval(Request $request): Approval|bool
    {
        $campaign = $this->focused();
        if ($campaign?->platform === 'linkedin') {
            $arguments = $request->all();
            $type = (string) ($arguments['entity_type'] ?? '');
            $ids = array_values(array_unique(array_filter(array_map('strval', (array) ($arguments['ids'] ?? [])))));
            if ($type === 'campaign' && $ids === []) {
                $ids = [(string) $campaign->external_campaign_id];
            }
            if ($ids === [] || count($ids) > self::MOST_PER_CALL) {
                return Approval::required(sprintf('Choose between 1 and %d exact LinkedIn entity IDs. No deletion is permitted.', self::MOST_PER_CALL));
            }
            try {
                $delivery = [];
                foreach ($ids as $id) {
                    $delivery[$id] = app(LinkedInManagement::class)->delivery($campaign, $type, $id, $this->actor->describe());
                }

                return $this->approvalBinding->request($request, $campaign, 'delete_entity', [
                    'entity_type' => $type, 'ids' => $ids, 'lifetime_delivery' => $delivery,
                    'delete_even_though_it_delivered' => (bool) ($arguments['delete_even_though_it_delivered'] ?? false),
                ]);
            } catch (Throwable $exception) {
                return Approval::required('Deletion is blocked because lifetime delivery could not be verified: '.$exception->getMessage());
            }
        }

        return $this->approvalBinding->request($request, $this->focused(), 'delete_entity');
    }

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

        $arguments = $request->all();
        $type = (string) ($arguments['entity_type'] ?? '');
        $confirmed = (bool) ($arguments['delete_even_though_it_delivered'] ?? false);

        // ad_group is Google's word for the level ad_set names on Meta. One
        // internal word from here on, as set_entity_status does. Normalised
        // before the check rather than inside the Google branch, because
        // LinkedIn never sends ad_group and the check below is shared.
        $type = $type === 'ad_group' ? 'ad_set' : $type;

        if (! in_array($type, ['campaign', 'ad_set', 'ad', 'creative', 'campaign_group'], true)) {
            return $this->json(['ok' => false, 'error' => 'Choose campaign, ad_set, ad_group, ad, creative, or campaign_group. LinkedIn supports campaign, campaign_group, creative, and ad; Meta and Google support campaign, ad_set or ad_group, and ad.']);
        }

        if ($campaign->platform === 'linkedin') {
            $ids = array_values(array_unique(array_filter(array_map('strval', (array) ($arguments['ids'] ?? [])))));
            if ($type === 'campaign' && $ids === []) {
                $ids = [(string) $campaign->external_campaign_id];
            }
            if ($ids === [] || count($ids) > self::MOST_PER_CALL) {
                return $this->json(['ok' => false, 'error' => sprintf('Choose between 1 and %d exact LinkedIn entity IDs.', self::MOST_PER_CALL)]);
            }
            $management = app(LinkedInManagement::class);
            $actor = $this->actor->describe();
            try {
                $review = null;
                if ($request->toolCallId() !== null) {
                    $review = $this->approvalBinding->consumeWithReviewedArguments($request, 'delete_entity', [
                        'entity_type' => $type,
                        'ids' => $ids,
                        'delete_even_though_it_delivered' => $confirmed,
                    ]);
                    if ($review === null) {
                        return $this->json(['ok' => false, 'error' => 'This deletion approval is no longer valid. Review the entities again.']);
                    }
                    $campaign = $review['campaign'];
                }

                $delivered = [];
                if ($review !== null) {
                    $reviewedDelivery = $review['reviewed_arguments']['lifetime_delivery'] ?? [];
                    foreach ($ids as $id) {
                        if (! is_array($reviewedDelivery[$id] ?? null)
                            || ! isset($reviewedDelivery[$id]['spend'], $reviewedDelivery[$id]['impressions'])) {
                            return $this->json(['ok' => false, 'error' => 'Lifetime delivery was not verified for every entity. Nothing was deleted.']);
                        }
                        if ($reviewedDelivery[$id]['spend'] > 0 || $reviewedDelivery[$id]['impressions'] > 0) {
                            $delivered[$id] = $reviewedDelivery[$id];
                        }
                    }
                } else {
                    foreach ($ids as $id) {
                        $management->entity($campaign, $type, $id, $actor);
                        $delivery = $management->delivery($campaign, $type, $id, $actor);
                        if ($delivery['spend'] > 0 || $delivery['impressions'] > 0) {
                            $delivered[$id] = $delivery;
                        }
                    }
                }
                if (! $confirmed && $delivered !== []) {
                    return $this->json(['ok' => false, 'error' => 'This has delivered, so it was not deleted.',
                        'delivered' => $delivered,
                        'note' => 'Tell the user the spend, currency and impressions for each entity, that deletion cannot be undone, and offer pausing it instead. Only after they confirm again may delete_even_though_it_delivered be set.']);
                }
            } catch (Throwable $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }
            $results = [];
            $failed = [];
            foreach ($ids as $id) {
                try {
                    $results[] = $management->delete($campaign, $type, $id, $actor, $confirmed);
                } catch (Throwable $exception) {
                    $failed[$id] = $exception->getMessage();
                }
            }

            return $this->json(['ok' => $failed === [], 'results' => $results, 'failed' => $failed,
                'note' => 'Pending deletion is not confirmed removal. Keep its IDs and report individual failures. No children were deleted implicitly.']);
        }

        if (! in_array($campaign->platform, ['meta', 'google'], true)) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Deleting is only available on Meta, Google and LinkedIn. This campaign is on %s.', ucfirst((string) $campaign->platform)),
            ]);
        }

        if (! in_array($type, ['campaign', 'ad_set', 'ad'], true)) {
            return $this->json(['ok' => false, 'error' => 'Meta and Google support campaign, ad_set or ad_group, and ad here.']);
        }

        if (! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('This campaign has not been published, so there is nothing on %s to delete.', ucfirst((string) $campaign->platform)),
                'note' => 'A draft is removed by abandoning it, not by this. Do not describe this as a failure.',
            ]);
        }

        $ids = array_values(array_unique(array_filter(array_map(
            static fn (mixed $id): string => trim((string) $id),
            (array) ($arguments['ids'] ?? []),
        ))));

        // The campaign in focus needs no id: it is the thing in hand, and asking
        // the model to repeat it back is one more chance to get it wrong.
        if ($type === 'campaign' && $ids === []) {
            $ids = [(string) $campaign->external_campaign_id];
        }

        if ($ids === []) {
            return $this->json([
                'ok' => false,
                'error' => 'No ids were given. Call list_campaign_structure and use the ids it returns.',
            ]);
        }

        if (count($ids) > self::MOST_PER_CALL) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Delete up to %d at a time. This asked for %d.', self::MOST_PER_CALL, count($ids)),
            ]);
        }

        if ($campaign->platform === 'google') {
            return $this->handleGoogle($campaign, $type, $ids, $confirmed);
        }

        try {
            if ($unknown = array_values(array_diff($ids, $this->idsUnder($campaign, $type)))) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('%s not part of this campaign, so nothing was deleted.', implode(', ', $unknown)),
                    'note' => 'Call list_campaign_structure for the current ids. Do not try these again.',
                ]);
            }

            if (! $confirmed && $delivered = $this->delivered($campaign, $ids)) {
                return $this->json([
                    'ok' => false,
                    'error' => 'This has delivered, so it was not deleted.',
                    'delivered' => $delivered,
                    'note' => 'Tell the user exactly what each one spent and how many impressions it had, '
                        .'that deleting cannot be undone, and that pausing it instead keeps it restartable. '
                        .'Only if they confirm after hearing that, call this again with '
                        .'delete_even_though_it_delivered set.',
                ]);
            }
        } catch (MetaException $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'Meta could not be read, so nothing was deleted. Do not retry without checking.',
            ]);
        }

        return $this->remove($campaign, $type, $ids);
    }

    /**
     * The same three guards on Google, against Google's own structure.
     *
     * Delivery is read all-time rather than over a window: a campaign that
     * spent and then stopped must not read as never having run. Verified
     * against the live account, where a campaign that never started reads zero
     * on both counts and its neighbours read six figures of micros.
     *
     * Children are not removed first. Google takes a campaign's ad groups and
     * ads with it, unlike Meta, which refuses a parent that still has children.
     *
     * @param  list<string>  $ids
     */
    private function handleGoogle(Campaign $campaign, string $type, array $ids, bool $confirmed): Stringable|string
    {
        $connection = GoogleAdsConnection::shared();

        if ($connection === null) {
            return $this->json([
                'ok' => false,
                'error' => ucfirst(GoogleAdsConnection::missingReason()).'.',
                'note' => 'Nothing was deleted. 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);
        $level = match ($type) {
            'ad_set' => 'ad_group',
            'ad' => 'ad',
            default => 'campaign',
        };

        try {
            $structure = $google->readCampaignStructure($connection, (string) $campaign->external_campaign_id);

            // The campaign level is checked too, which it was not.
            //
            // Only the children were matched against the structure, so a
            // campaign id the model carried over from an earlier turn - or
            // invented in the right shape - was sent straight to
            // campaigns:mutate as a remove. The id is never read for
            // ownership, and the approval card names the campaign in focus
            // rather than the id, so the buyer approves deleting one campaign
            // and a different one is destroyed. Meta has always diffed against
            // idsUnder(), which returns the campaign's own id at this level;
            // this is the same guard, which the class docblock already claims.
            $known = match ($level) {
                'campaign' => [(string) $campaign->external_campaign_id],
                'ad_group' => array_column($structure['ad_groups'], 'id'),
                default => array_column($structure['ads'], 'id'),
            };

            if ($unknown = array_values(array_diff($ids, array_map('strval', $known)))) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('%s not part of this campaign, so nothing was deleted.', implode(', ', $unknown)),
                    'note' => 'Call list_campaign_structure for the current ids. Do not try these again.',
                ]);
            }

            $delivery = $google->readLifetimeDelivery($connection, $level, $ids);
            $delivered = array_filter($delivery, fn (array $seen): bool => $seen['spend'] > 0 || $seen['impressions'] > 0);
            if (! $confirmed && $delivered !== []) {
                return $this->json([
                    'ok' => false,
                    'error' => 'This has delivered, so it was not deleted.',
                    'delivered' => $delivered,
                    'note' => 'Tell the user exactly what each one spent and how many impressions it had, '
                        .'that deleting cannot be undone, and that pausing it instead keeps it restartable. '
                        .'Only if they confirm after hearing that, call this again with '
                        .'delete_even_though_it_delivered set.',
                ]);
            }
        } catch (Throwable $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'Google could not be read, so nothing was deleted. Do not retry without checking.',
            ]);
        }

        $adGroupOf = collect($structure['ads'])->pluck('ad_group_id', 'id');
        $deleted = [];
        $failed = [];

        foreach ($ids as $id) {
            try {
                $google->removeEntity($connection, $level, $id, $level === 'ad' ? $adGroupOf->get($id) : null);
                $deleted[] = $id;
            } catch (Throwable $e) {
                $failed[$id] = $e->getMessage();
            }
        }

        // Only for what Google confirmed, and only because removeResource now
        // throws on a refusal. While it swallowed them, every removal looked
        // like a success and clearing the id here is what left live campaigns
        // with no record of them.
        if ($level === 'campaign' && in_array((string) $campaign->external_campaign_id, $deleted, true)) {
            $campaign->forceFill(['external_campaign_id' => null, 'activated_at' => null, 'status' => 'draft'])->save();
        }

        return $this->json(array_filter([
            'ok' => $deleted !== [],
            'entity_type' => $level,
            'deleted' => $deleted,
            'failed' => $failed ?: null,
            'note' => $failed !== []
                ? 'Name what failed and say it is still on the account. Do not describe this as done.'
                : sprintf(
                    '%d %s(s) permanently deleted. Say so in one line and do not offer to restore them - '
                        .'Google cannot.',
                    count($deleted),
                    str_replace('_', ' ', $level),
                ),
        ], static fn (mixed $value): bool => $value !== null));
    }

    /**
     * Deepest first, because Meta refuses to delete a parent that still has
     * children - the same order the publish rollback uses.
     *
     * @param  list<string>  $ids
     */
    private function remove(Campaign $campaign, string $type, array $ids): string
    {
        $meta = $this->meta->on($campaign->id, $this->actor->describe());
        $deleted = [];
        $failed = [];

        foreach ($ids as $id) {
            try {
                foreach ($this->childrenOf($meta, $campaign, $type, $id) as $childId) {
                    $meta->delete($childId, $campaign->ad_account_id);
                }

                $meta->delete($id, $campaign->ad_account_id)
                    ? $deleted[] = $id
                    : $failed[$id] = 'Meta did not confirm the delete.';
            } catch (Throwable $e) {
                $failed[$id] = $e->getMessage();
            }
        }

        // Only now, and only for what Meta confirmed. Clearing the id on an
        // unconfirmed delete is what left live campaigns with no record at all.
        if ($type === 'campaign' && in_array((string) $campaign->external_campaign_id, $deleted, true)) {
            $campaign->forceFill(['external_campaign_id' => null, 'activated_at' => null, 'status' => 'draft'])->save();
        }

        return $this->json(array_filter([
            'ok' => $deleted !== [],
            'entity_type' => $type,
            'deleted' => $deleted,
            'failed' => $failed ?: null,
            'note' => $failed !== []
                ? 'Name what failed and say it is still on the account. Do not describe this as done.'
                : sprintf('%d %s(s) permanently deleted. Say so in one line and do not offer to restore them - Meta cannot.', count($deleted), str_replace('_', ' ', $type)),
        ], static fn (mixed $value): bool => $value !== null));
    }

    /**
     * The objects that have to go first.
     *
     * Only for a campaign. An ad set's ads are left to Meta, which removes them
     * with their parent; a campaign with ad sets is refused outright.
     *
     * @return list<string>
     */
    private function childrenOf(Meta $meta, Campaign $campaign, string $type, string $id): array
    {
        if ($type !== 'campaign') {
            return [];
        }

        $ads = array_map(
            static fn (array $ad): string => (string) ($ad['id'] ?? ''),
            $meta->ads($id, $campaign->ad_account_id, fresh: true),
        );
        $adSets = array_map(
            static fn (array $adSet): string => (string) ($adSet['id'] ?? ''),
            $meta->adSets($id, $campaign->ad_account_id, fresh: true),
        );

        return array_values(array_filter([...$ads, ...$adSets]));
    }

    /**
     * Which of these have ever run, and what they spent doing it.
     *
     * @param  list<string>  $ids
     * @return array<string, array{spend: float, impressions: int}>
     */
    private function delivered(Campaign $campaign, array $ids): array
    {
        $delivered = [];

        foreach ($ids as $id) {
            $seen = $this->meta->on($campaign->id, $this->actor->describe())
                ->lifetimeDelivery($id, $campaign->ad_account_id);

            if ($seen['spend'] > 0 || $seen['impressions'] > 0) {
                $delivered[$id] = $seen;
            }
        }

        return $delivered;
    }

    /**
     * The ids genuinely under this campaign, read fresh.
     *
     * @return list<string>
     */
    private function idsUnder(Campaign $campaign, string $type): array
    {
        $external = (string) $campaign->external_campaign_id;

        if ($type === 'campaign') {
            return [$external];
        }

        $meta = $this->meta->on($campaign->id, $this->actor->describe());

        $rows = $type === 'ad_set'
            ? $meta->adSets($external, $campaign->ad_account_id, fresh: true)
            : $meta->ads($external, $campaign->ad_account_id, fresh: true);

        return array_values(array_filter(array_map(
            static fn (array $row): string => (string) ($row['id'] ?? ''),
            $rows,
        )));
    }
}
