<?php

namespace App\Campaigns\Manager\Editing\Writers;

use App\Campaigns\Manager\Editing\AdvancedEditFields;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\Editing\EditRefused;
use App\Campaigns\Manager\Editing\EntityWriter;
use App\Models\Campaign;
use App\Models\CampaignPlatformEntity;
use App\Services\Meta\Meta;
use App\Support\CurrencyMinorUnits;
use Carbon\CarbonImmutable;
use DateTimeInterface;
use Throwable;

/**
 * Names, statuses, budgets, bid amounts, ad set run dates and the plain parts
 * of an ad set's targeting (countries, ages, gender, placements), through the same
 * Graph update the chat uses. Status goes to Graph too, never the MCP: its
 * update tool turns a live object into an unpublished draft.
 *
 * Meta takes money in the account currency's minor units. Only the budget the
 * object already holds is ever sent, so this cannot turn an Advantage campaign
 * budget into ad set budgets or swap daily for lifetime.
 */
class MetaEntityWriter implements EntityWriter
{
    /** @var array<string, list<string>> */
    private const array FIELDS = [
        'campaign' => ['name', 'status', 'daily_budget', 'lifetime_budget', 'bid_strategy', 'spend_cap'],
        'ad_set' => [
            'name', 'status', 'daily_budget', 'lifetime_budget', 'bid_strategy', 'bid_amount',
            'daily_min_spend_target', 'daily_spend_cap', 'lifetime_min_spend_target', 'lifetime_spend_cap',
            'frequency_max', 'frequency_days', 'countries', 'age_min', 'age_max', 'genders', 'publisher_platforms',
            'start_time', 'end_time',
            ...AdvancedEditFields::META_TARGETING,
            'pacing_type', 'adset_schedule', 'roas_floor', 'budget_schedules',
        ],
        'ad' => ['name', 'status'],
    ];

    /** The most ads Meta copies along with an ad set in one call: fewer than three objects in all. */
    private const int MAX_COPIED_ADS = 1;

    public function __construct(private readonly Meta $meta) {}

    public function write(Campaign $campaign, CampaignPlatformEntity $entity, array $patch, string $actor): void
    {
        $allowed = self::FIELDS[$entity->entity_type] ?? [];

        if ($patch === [] || array_diff(array_keys($patch), $allowed) !== []) {
            throw new EditRefused(sprintf('Only %s can be changed on a Meta %s from here.', implode(', ', $allowed) ?: 'nothing', str_replace('_', ' ', $entity->entity_type)));
        }

        $fields = [];
        $schedules = $patch['budget_schedules'] ?? null;
        unset($patch['budget_schedules']);

        // The cap is one spec on Meta; its two halves arrive as two fields.
        if (array_intersect_key($patch, ['frequency_max' => true, 'frequency_days' => true]) !== []) {
            $fields['frequency_control_specs'] = self::frequency($entity, $patch);
            unset($patch['frequency_max'], $patch['frequency_days']);
        }

        // Targeting is one object on Meta: the parts changed here go into the
        // targeting just read, so interests and audiences are sent back as they are.
        $targeting = array_filter($patch, fn (string $field): bool => EditCapabilities::isTargeting($field), ARRAY_FILTER_USE_KEY);

        if ($targeting !== []) {
            $fields['targeting'] = self::targeting($entity, $targeting);
            $patch = array_diff_key($patch, $targeting);
        }

        foreach ($patch as $field => $value) {
            $fields[$field] = match (true) {
                $field === 'name' => (string) $value,
                $field === 'status' => self::status($value),
                $field === 'bid_strategy' => self::strategy($value),
                $field === 'roas_floor' => json_encode([
                    ...(array) data_get($entity->settings, 'bid_constraints', []),
                    'roas_average_floor' => (int) round((float) $value * 10000),
                ], JSON_THROW_ON_ERROR),
                in_array($field, ['pacing_type', 'adset_schedule'], true) => json_encode($value, JSON_THROW_ON_ERROR),
                $field === 'spend_cap' && blank($value) => EditCapabilities::META_NO_SPEND_CAP,
                blank($value) => throw new EditRefused('An ad set spend limit is changed here, not removed.'),
                // ISO 8601 with its offset: a bare local time is read in the
                // ad account's zone and would shift silently.
                EditCapabilities::isSchedule($field) => CarbonImmutable::parse((string) $value)->format(DateTimeInterface::ATOM),
                default => CurrencyMinorUnits::toMinor((float) $value, EditCapabilities::currency($entity)),
            };
        }

        foreach (['roas_floor' => 'bid_constraints'] as $alias => $native) {
            if (array_key_exists($alias, $fields)) {
                $fields[$native] = $fields[$alias];
                unset($fields[$alias]);
            }
        }

        if (array_key_exists('adset_schedule', $patch) && ! array_key_exists('pacing_type', $patch)) {
            $pacing = array_values(array_diff((array) data_get($entity->settings, 'pacing_type', ['standard']), ['day_parting']));
            $fields['pacing_type'] = json_encode($patch['adset_schedule'] === [] ? $pacing : [...$pacing, 'day_parting'], JSON_THROW_ON_ERROR);
        }

        $meta = $this->meta->on($campaign->id, $actor);
        if ($fields !== []) {
            $meta->updateLiveEntity((string) $campaign->ad_account_id, $entity->external_id, $fields);
        }
        if ($schedules !== null) {
            $meta->replaceBudgetSchedules((string) $campaign->ad_account_id, $entity->external_id, (array) data_get($entity->settings, 'budget_schedules'), $schedules);
        }
    }

    /** @param  array<string, mixed>  $patch */
    private static function frequency(CampaignPlatformEntity $entity, array $patch): string
    {
        $value = fn (string $field): int => (int) (array_key_exists($field, $patch) ? $patch[$field] : EditCapabilities::current($entity, $field));
        [$max, $days] = [$value('frequency_max'), $value('frequency_days')];

        if ($max < 1 || $days < 1) {
            throw new EditRefused('A frequency cap needs both how many times and over how many days.');
        }

        return (string) json_encode([['event' => 'IMPRESSIONS', 'interval_days' => $days, 'max_frequency' => $max]]);
    }

    /** @param  array<string, mixed>  $changes */
    private static function targeting(CampaignPlatformEntity $entity, array $changes): string
    {
        $targeting = data_get($entity->settings, 'targeting');

        if (! is_array($targeting)) {
            throw new EditRefused('Meta did not report this ad set\'s targeting, so it was not changed.');
        }

        foreach ($changes as $field => $value) {
            $value = EditCapabilities::normalize($entity, $field, $value);

            if (in_array($field, AdvancedEditFields::META_TARGETING, true)) {
                if ($field === 'advantage_audience') {
                    data_set($targeting, 'targeting_automation.advantage_audience', (int) $value);
                } elseif ($value === []) {
                    unset($targeting[$field]);
                } else {
                    $targeting[$field] = $value;
                }

                if ($field === 'flexible_spec') {
                    // Legacy interests/behaviours are aliases of flexible_spec.
                    unset($targeting['interests'], $targeting['behaviors']);
                }

                continue;
            }

            match ($field) {
                'countries' => $value !== []
                    ? data_set($targeting, 'geo_locations.countries', $value)
                    : throw new EditRefused('An ad set needs at least one country.'),
                'age_min', 'age_max' => $targeting[$field] = $value ?? throw new EditRefused('An age range needs both ends.'),
                'genders' => self::genders($targeting, $value),
                'publisher_platforms' => self::platforms($targeting, $value),
            };
        }

        return (string) json_encode($targeting);
    }

    /** @param  array<string, mixed>  $targeting */
    private static function genders(array &$targeting, string $value): void
    {
        unset($targeting['genders']);

        if ($value !== 'all') {
            $targeting['genders'] = [$value === 'men' ? 1 : 2];
        }
    }

    /**
     * @param  array<string, mixed>  $targeting
     * @param  list<string>  $platforms
     */
    private static function platforms(array &$targeting, array $platforms): void
    {
        $unknown = array_diff($platforms, array_keys(EditCapabilities::META_PLATFORMS));

        if ($unknown !== []) {
            throw new EditRefused(sprintf('%s is not a placement offered here.', implode(', ', $unknown)));
        }

        // A platform that goes takes its positions with it; with none listed,
        // Meta places the ads itself.
        foreach (array_keys(EditCapabilities::META_PLATFORMS) as $platform) {
            if (! in_array($platform, $platforms, true)) {
                unset($targeting[$platform.'_positions']);
            }
        }

        unset($targeting['publisher_platforms']);

        if ($platforms !== []) {
            $targeting['publisher_platforms'] = $platforms;
        }
    }

    private static function strategy(mixed $value): string
    {
        return in_array($value, ['LOWEST_COST_WITHOUT_CAP', 'COST_CAP', 'LOWEST_COST_WITH_BID_CAP', 'LOWEST_COST_WITH_MIN_ROAS'], true)
            ? $value
            : throw new EditRefused('Choose highest volume, cost per result goal or bid cap.');
    }

    private static function status(mixed $value): string
    {
        return in_array($value, ['ACTIVE', 'PAUSED', 'ARCHIVED'], true)
            ? $value
            : throw new EditRefused('Choose on, paused or archived.');
    }

    public function delivery(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): array
    {
        $seen = $this->meta->on($campaign->id, $actor)->lifetimeDelivery($entity->external_id, $campaign->ad_account_id);

        return ['spend' => (float) $seen['spend'], 'impressions' => (int) $seen['impressions']];
    }

    /**
     * Deepest first for a campaign, because Meta refuses a parent that still
     * has children; an ad set's ads go with it. The same order the chat's
     * delete and the publish rollback use.
     */
    public function delete(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): bool
    {
        $meta = $this->meta->on($campaign->id, $actor);

        if ($entity->entity_type === 'campaign') {
            $children = [
                ...$meta->ads($entity->external_id, $campaign->ad_account_id, fresh: true),
                ...$meta->adSets($entity->external_id, $campaign->ad_account_id, fresh: true),
            ];

            foreach (array_filter(array_map(fn (array $row): string => (string) ($row['id'] ?? ''), $children)) as $childId) {
                $meta->delete($childId, $campaign->ad_account_id);
            }
        }

        if (! $meta->delete($entity->external_id, $campaign->ad_account_id)) {
            throw new EditRefused('Meta did not confirm the delete.');
        }

        return true;
    }

    /** Meta's own copy, ads included for an ad set or a campaign, created paused. */
    public function duplicate(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): string
    {
        $meta = $this->meta->on($campaign->id, $actor);
        $parent = (string) $entity->parent_external_id;

        if ($entity->entity_type === 'campaign') {
            return $this->duplicateCampaign($campaign, $entity, $meta);
        }

        if ($entity->entity_type === 'ad_set') {
            return $this->copyAdSetInto($campaign, $entity, $parent ?: (string) $campaign->external_campaign_id, $meta, rollback: true);
        }

        $copied = match ($entity->entity_type) {
            'ad' => $parent !== ''
                ? $meta->copyAd($entity->external_id, $parent, $campaign->ad_account_id, 'PAUSED')
                : throw new EditRefused('Meta did not say which ad set this ad is in, so it was not copied.'),
            default => throw new EditRefused('Only an ad set or an ad is copied on Meta from here.'),
        };

        $id = (string) ($copied['copied_ad_id'] ?? $copied['id'] ?? '');

        return $id !== '' ? $id : throw new EditRefused('Meta accepted the copy but did not say what it is called.');
    }

    public function duplicateWithEvent(Campaign $campaign, CampaignPlatformEntity $entity, string $actor, string $event): string
    {
        $capabilities = app(EditCapabilities::class);
        if (($reason = $capabilities->eventCopyRefusal($entity)) !== null) {
            throw new EditRefused($reason);
        }
        if (! array_key_exists($event, EditCapabilities::options($entity, 'conversion_event'))
            || $event === data_get($entity->settings, 'promoted_object.custom_event_type')) {
            throw new EditRefused('Choose an available standard conversion event.');
        }
        $meta = $this->meta->on($campaign->id, $actor);
        $account = (string) $campaign->ad_account_id;
        $source = $meta->readAdSetForEventCopy($entity->external_id, $account);
        if ((string) ($source['campaign_id'] ?? '') !== (string) $campaign->external_campaign_id
            || (string) ($source['id'] ?? '') !== $entity->external_id
            || ltrim((string) ($source['account_id'] ?? ''), 'act_') !== ltrim($account, 'act_')) {
            throw new EditRefused('Meta returned an ad set outside the requested campaign or account.');
        }
        if (! is_array($source['targeting'] ?? null)
            || data_get($source, 'promoted_object.pixel_id') !== data_get($entity->settings, 'promoted_object.pixel_id')
            || data_get($source, 'promoted_object.custom_event_type') !== data_get($entity->settings, 'promoted_object.custom_event_type')
            || ($source['optimization_goal'] ?? null) !== data_get($entity->settings, 'optimization_goal')) {
            throw new EditRefused('The original targeting, pixel, goal or conversion event could not be confirmed. Refresh and propose the copy again.');
        }
        if (filled($source['end_time'] ?? null) && ! CarbonImmutable::parse($source['end_time'])->isFuture()) {
            throw new EditRefused('The original run has ended; its schedule cannot be preserved on a new conversion-event copy.');
        }
        $copyId = $meta->createAdSetWithEvent($account, (string) $campaign->external_campaign_id, $source, $event);
        try {
            foreach (self::children($campaign, $entity->external_id, 'ad') as $ad) {
                $copied = $meta->copyAd($ad->external_id, $copyId, $account, 'PAUSED');
                if (blank($copied['copied_ad_id'] ?? $copied['id'] ?? null)) {
                    throw new EditRefused('Meta did not identify a copied ad.');
                }
            }
            $schedules = (array) data_get($entity->settings, 'budget_schedules', []);
            if ($schedules !== []) {
                $meta->replaceBudgetSchedules($account, $copyId, [], array_map(
                    fn (array $schedule): array => array_diff_key($schedule, ['id' => true]), $schedules,
                ));
            }
        } catch (Throwable $exception) {
            try {
                $this->discard($meta, $copyId, $account, adSet: true, strict: true);
            } catch (Throwable $cleanup) {
                throw new EditRefused('Copy failed: '.$exception->getMessage().'; cleanup of paused copy '.$copyId.' also failed: '.$cleanup->getMessage(), previous: $exception);
            }

            throw $exception;
        }

        return $copyId;
    }

    /**
     * The campaign first, on its own, then each ad set into it. A copy that
     * fails part way is deleted again, so a half-built campaign is never left
     * behind.
     */
    private function duplicateCampaign(Campaign $campaign, CampaignPlatformEntity $entity, Meta $meta): string
    {
        $account = (string) $campaign->ad_account_id;
        $copied = $meta->copyCampaign($entity->external_id, $account, 'PAUSED');
        $copyId = (string) ($copied['copied_campaign_id'] ?? $copied['id'] ?? '');

        if ($copyId === '') {
            throw new EditRefused('Meta accepted the copy but did not say what it is called.');
        }

        try {
            foreach (self::children($campaign, $entity->external_id, 'ad_set') as $adSet) {
                $this->copyAdSetInto($campaign, $adSet, $copyId, $meta, rollback: false);
            }
        } catch (Throwable $exception) {
            $this->discard($meta, $copyId, $account);

            throw $exception;
        }

        return $copyId;
    }

    /**
     * Meta refuses a copy of more than two objects in one call, the ad set
     * included, so one with more than a single ad is copied bare and its ads
     * one by one. With $rollback a copy that fails part way is deleted again.
     */
    private function copyAdSetInto(Campaign $campaign, CampaignPlatformEntity $adSet, string $campaignId, Meta $meta, bool $rollback): string
    {
        $account = (string) $campaign->ad_account_id;
        $ads = self::children($campaign, $adSet->external_id, 'ad');
        $deep = count($ads) <= self::MAX_COPIED_ADS;
        $copied = $meta->copyAdSet($adSet->external_id, $campaignId, $account, 'PAUSED', $deep);
        $copyId = (string) ($copied['copied_adset_id'] ?? $copied['id'] ?? '');

        if ($copyId === '') {
            throw new EditRefused(sprintf('Meta did not say what the copy of ad set %s is called.', $adSet->name ?: $adSet->external_id));
        }

        try {
            foreach ($deep ? [] : $ads as $ad) {
                $meta->copyAd($ad->external_id, $copyId, $account, 'PAUSED');
            }
        } catch (Throwable $exception) {
            if ($rollback) {
                $this->discard($meta, $copyId, $account, adSet: true);
            }

            throw $exception;
        }

        return $copyId;
    }

    /** @return list<CampaignPlatformEntity> */
    private static function children(Campaign $campaign, string $parentId, string $type): array
    {
        return $campaign->platformEntities()
            ->where('entity_type', $type)
            ->where('parent_external_id', $parentId)
            ->whereNull('removed_at')
            ->whereNotIn('status', ['DELETED', 'PENDING_DELETION'])
            ->orderBy('id')
            ->get()
            ->all();
    }

    /** Best effort: a copy that could not be finished is taken down, deepest first. */
    private function discard(Meta $meta, string $copyId, string $account, bool $adSet = false, bool $strict = false): void
    {
        try {
            $children = [...$meta->ads($copyId, $account, fresh: true), ...($adSet ? [] : $meta->adSets($copyId, $account, fresh: true))];

            foreach (array_filter(array_map(fn (array $row): string => (string) ($row['id'] ?? ''), $children)) as $childId) {
                $deleted = $meta->delete($childId, $account);
                if ($strict && ! $deleted) {
                    throw new EditRefused('Meta did not confirm removal of copied child '.$childId.'.');
                }
            }

            $deleted = $meta->delete($copyId, $account);
            if ($strict && ! $deleted) {
                throw new EditRefused('Meta did not confirm removal of copy '.$copyId.'.');
            }
        } catch (Throwable $exception) {
            report($exception);
            if ($strict) {
                throw $exception;
            }
        }
    }
}
