<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Models\Asset;
use App\Models\Campaign;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

/**
 * Decide which creative each ad uses.
 *
 * Copy and creative arrive in either order: the ads are usually written before
 * the user has uploaded anything, so something has to pair them afterwards.
 * Without this the ads keep no asset, the publish gate refuses, and the agent
 * has no way to act on "use one image across two ads".
 *
 * The same asset may back several ads on purpose. That is how one image ships
 * three ads that differ only by copy.
 *
 * Ads that are already live are left alone. The image is part of the creative
 * and Meta cannot swap one out, so repointing the row would have left our
 * record naming an image the ad was not serving. edit_entity does it properly,
 * by building a new creative under the same ad.
 */
class AttachCreatives implements Tool
{
    use ActsOnFocusedCampaign;

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

    public function description(): Stringable|string
    {
        return 'Attach creatives to the ads of the campaign in focus. Pass mapping to control '
            .'which asset each ad uses, or call with no arguments to spread the attached '
            .'creatives across the ads. The same asset may be used by several ads. On a Google '
            .'Performance Max campaign this is also where the brand logo is named, with '
            .'logo_asset_id - Google will not run an asset group without one.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'mapping' => $schema->array()->items(
                $schema->object([
                    'ad_id' => $schema->integer()->description('The ad id shown in the campaign state.')->required(),
                    'asset_id' => $schema->integer()->description('The asset id to use for that ad.')->required(),
                ])
            )->description('Explicit ad to asset pairs. Omit to spread the available creatives automatically.'),
            'logo_asset_id' => $schema->integer()
                ->description('Google Performance Max only. Which attached creative is the brand logo. '
                    .'Google requires one on every asset group and it has to be square. Ask the user '
                    .'which it is rather than choosing for them: a marketing image sent as a logo is '
                    .'refused by Google as not being one.'),
        ];
    }

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

        $all = $campaign->ads()->orderBy('id')->get();

        if ($all->isEmpty()) {
            return $this->json(['ok' => false, 'error' => 'No ads written yet. Write the ad copy first.']);
        }

        $live = $all->filter(fn ($ad): bool => filled($ad->external_ad_id))->values();
        $ads = $all->filter(fn ($ad): bool => blank($ad->external_ad_id))->values();

        if ($ads->isEmpty()) {
            return $this->json([
                'ok' => false,
                'error' => 'Every ad on this campaign is already live, so their creatives cannot be changed here.',
                'live_ads' => $live->pluck('external_ad_id')->all(),
                'note' => 'edit_entity changes the image on a live ad, by building a new creative under the '
                    .'same ad. Offer that, and say Meta restarts the learning phase when it happens.',
            ]);
        }

        $assets = $this->workspace->artifacts(Asset::class)
            ->map(fn ($link) => $link->artifactable)
            ->filter()
            ->values();

        if ($assets->isEmpty()) {
            return $this->json([
                'ok' => false,
                'error' => 'No creatives are attached to this conversation. Ask the user to upload one.',
            ]);
        }

        $arguments = $request->all();

        if (array_key_exists('logo_asset_id', $arguments)) {
            if ($refusal = $this->recordLogo($campaign, $assets, $arguments['logo_asset_id'])) {
                return $refusal;
            }
        }

        $mapping = (array) ($arguments['mapping'] ?? []);

        $result = $mapping === []
            ? $this->spread($campaign, $ads, $assets, $live)
            : $this->apply($campaign, $ads, $assets, $mapping, $live);

        return $this->withLogoQuestion($campaign, $assets, $result);
    }

    /**
     * Which attached creative is the brand logo.
     *
     * Performance Max only. Google will not run an asset group without a logo
     * and will not accept a marketing image as one, so this is asked rather
     * than guessed: picking the wrong image is a policy refusal, not a
     * cosmetic one.
     *
     * Held on the campaign rather than on the asset, because being this
     * campaign's logo is a decision about this campaign; the same image can be
     * a logo in one and a marketing image in another.
     *
     * @param  Collection<int, Asset>  $assets
     */
    private function recordLogo(Campaign $campaign, $assets, mixed $assetId): ?string
    {
        if (($campaign->campaign_type ?? '') !== 'performance_max' || $campaign->platform !== 'google') {
            return $this->json([
                'ok' => false,
                'error' => 'A logo is only asked for on a Google Performance Max campaign. This one is not.',
                'note' => 'Attach the creatives without logo_asset_id.',
            ]);
        }

        $asset = $assets->firstWhere('id', (int) $assetId);

        if ($asset === null) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Asset %s is not attached to this conversation, so it cannot be the logo.', (string) $assetId),
                'note' => 'Offer the squares that are attached. Do not invent an asset id.',
            ]);
        }

        if (! in_array($asset->id, array_column($this->squareCandidates($assets), 'asset_id'), true)) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    '%s is not usable as a logo. Google needs a square image of at least 128x128.',
                    $asset->original_name ?: 'That creative',
                ),
                'logo_candidates' => $this->squareCandidates($assets),
                'note' => 'Offer these instead. If none of them is the brand logo, ask the user to upload one.',
            ]);
        }

        $campaign->update(['meta' => [...(array) $campaign->meta, 'google_logo_asset_id' => $asset->id]]);

        return null;
    }

    /**
     * The attached creatives that could be a logo, by id.
     *
     * Square and at least Google's minimum. Measured rather than assumed: the
     * ratio a creative was generated at is not necessarily the ratio of the
     * file on disk.
     *
     * @param  Collection<int, Asset>  $assets
     * @return list<array{asset_id: int, name: string, size: string}>
     */
    private function squareCandidates($assets): array
    {
        $candidates = [];

        foreach ($assets as $asset) {
            if ($asset->kind !== 'image') {
                continue;
            }

            $disk = Storage::disk($asset->disk ?: 'local');

            if (! $disk->exists($asset->path)) {
                continue;
            }

            $size = @getimagesizefromstring($disk->get($asset->path));

            if (! is_array($size) || $size[0] < 128 || $size[1] < 128 || $size[0] !== $size[1]) {
                continue;
            }

            $candidates[] = [
                'asset_id' => $asset->id,
                'name' => $asset->original_name ?: 'Creative '.$asset->id,
                'size' => $size[0].'x'.$size[1],
            ];
        }

        return $candidates;
    }

    /**
     * Ask for the logo once the creatives are on, if this campaign needs one.
     *
     * Added to the result rather than replacing it, so attaching still reports
     * what it did and the logo is the next thing rather than the only thing.
     *
     * @param  Collection<int, Asset>  $assets
     */
    private function withLogoQuestion(Campaign $campaign, $assets, string $result): string
    {
        if (($campaign->campaign_type ?? '') !== 'performance_max'
            || $campaign->platform !== 'google'
            || filled($campaign->fresh()->meta['google_logo_asset_id'] ?? null)) {
            return $result;
        }

        $decoded = json_decode($result, true);

        if (! is_array($decoded) || ($decoded['ok'] ?? false) !== true) {
            return $result;
        }

        $candidates = $this->squareCandidates($assets);

        return $this->json([
            ...$decoded,
            'logo_needed' => true,
            'logo_candidates' => $candidates,
            'note' => ($decoded['note'] ?? '').' Performance Max also needs a brand logo, which Google '
                .'will not run an asset group without. '.($candidates === []
                    ? 'None of the attached creatives is a square of at least 128x128, so ask the user to upload the logo.'
                    : 'Ask which of the squares listed is the logo and call this again with logo_asset_id. Do not pick one yourself.'),
        ]);
    }

    /** Round robin, so fewer creatives than ads still fills every ad. */
    private function spread($campaign, $ads, $assets, $live): string
    {
        foreach ($ads as $index => $ad) {
            $ad->update(['asset_id' => $assets[$index % $assets->count()]->id]);
        }

        return $this->json(array_filter([
            'ok' => true,
            'campaign_id' => $campaign->id,
            'attached' => $ads->map(fn ($ad): array => [
                'ad_id' => $ad->id,
                'asset_id' => $ad->fresh()->asset_id,
            ])->all(),
            'left_alone_because_they_are_live' => $live->pluck('external_ad_id')->all() ?: null,
            'note' => $live->isEmpty() ? null
                : 'The live ads keep the image they launched with. Say so, and offer edit_entity for each one.',
        ], static fn (mixed $value): bool => $value !== null));
    }

    /** @param list<array{ad_id:int,asset_id:int}> $mapping */
    private function apply($campaign, $ads, $assets, array $mapping, $live): string
    {
        $adIds = $ads->pluck('id')->all();
        $assetIds = $assets->pluck('id')->all();
        $liveIds = $live->pluck('id')->all();

        foreach ($mapping as $pair) {
            $adId = (int) ($pair['ad_id'] ?? 0);
            $assetId = (int) ($pair['asset_id'] ?? 0);

            // Named rather than skipped, and before anything is written: a
            // mapping that half applies is worse than one that is refused.
            if (in_array($adId, $liveIds, true)) {
                return $this->json([
                    'ok' => false,
                    'error' => "Ad {$adId} is already live, so its creative cannot be changed here. Nothing was attached.",
                    'note' => 'edit_entity changes the image on a live ad, by building a new creative under the '
                        .'same ad. Offer that for this ad, and say Meta restarts the learning phase.',
                ]);
            }

            if (! in_array($adId, $adIds, true)) {
                return $this->json([
                    'ok' => false,
                    'error' => "Ad {$adId} does not belong to this campaign.",
                    'ads' => $adIds,
                ]);
            }

            if (! in_array($assetId, $assetIds, true)) {
                return $this->json([
                    'ok' => false,
                    'error' => "Asset {$assetId} is not attached to this conversation.",
                    'assets' => $assetIds,
                ]);
            }
        }

        foreach ($mapping as $pair) {
            $ads->firstWhere('id', (int) $pair['ad_id'])->update(['asset_id' => (int) $pair['asset_id']]);
        }

        $unassigned = $campaign->ads()->whereNull('asset_id')->pluck('id')->all();

        return $this->json(array_filter([
            'ok' => true,
            'campaign_id' => $campaign->id,
            'attached' => $mapping,
            'still_without_a_creative' => $unassigned ?: null,
            'left_alone_because_they_are_live' => $live->pluck('external_ad_id')->all() ?: null,
        ], fn ($v) => $v !== null));
    }
}
