<?php

namespace App\Campaigns\Manager;

use App\Models\Campaign;
use App\Models\CampaignPlatformDrift;
use App\Models\CampaignPlatformEntity;
use App\Models\CampaignSyncRun;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use InvalidArgumentException;
use RuntimeException;
use Throwable;

/**
 * Brings the stored picture of a campaign up to date with its platform.
 *
 * Read-only towards the platform. What it writes is our record of what the
 * platform said, and the rules for that record are the point of this class:
 *
 * - A failed read changes nothing that was stored. The run is kept as failed,
 *   and the last good snapshot stays visible with its age, because "Meta was
 *   unreachable" must not look like "this campaign is now empty".
 * - Rows missing from a read count as removed only for entity types that were
 *   read in full. A read that stopped at a page limit says nothing about what
 *   lies beyond it.
 * - The first successful read is the baseline. Every object in it already
 *   existed; reporting them all as added would bury the changes that matter.
 * - Differences between reads are recorded per field without an author.
 *   Between two reads a change can come from a platform UI, an automated
 *   platform rule, or this product's own tools.
 */
class CampaignSynchronizer
{
    /** Longest one read may hold the per-campaign lock. */
    private const int LOCK_SECONDS = 120;

    public function __construct(private readonly StructureReaders $readers) {}

    /**
     * @throws InvalidArgumentException when the campaign cannot be synced at all
     * @throws RuntimeException when a refresh of this campaign is already running
     */
    public function sync(Campaign $campaign, string $trigger = 'manual', ?string $actor = null): CampaignSyncRun
    {
        if (! $campaign->isPublished()) {
            throw new InvalidArgumentException('This campaign has not been published, so there is nothing on the platform to read.');
        }

        $reader = $this->readers->for((string) $campaign->platform);
        $lock = Cache::lock('campaign-manager:sync:'.$campaign->id, self::LOCK_SECONDS);

        if (! $lock->get()) {
            throw new RuntimeException('This campaign is already being refreshed. Try again in a moment.');
        }

        try {
            $run = $campaign->syncRuns()->create([
                'platform' => $campaign->platform,
                'trigger' => $trigger,
                'status' => CampaignSyncRun::Running,
                'actor' => $actor,
                'started_at' => now(),
            ]);

            try {
                $snapshot = $reader->read($campaign, $actor);
            } catch (Throwable $exception) {
                if (! $exception instanceof RuntimeException) {
                    report($exception);
                }

                $run->update([
                    'status' => CampaignSyncRun::Failed,
                    'error' => Str::limit($exception->getMessage() ?: class_basename($exception), 1000),
                    'finished_at' => now(),
                ]);

                return $run;
            }

            try {
                DB::transaction(fn () => $this->record($campaign, $run, $snapshot));
            } catch (Throwable $exception) {
                $run->update([
                    'status' => CampaignSyncRun::Failed,
                    'error' => 'The platform was read, but saving the result failed.',
                    'finished_at' => now(),
                ]);

                throw $exception;
            }

            return $run->refresh();
        } finally {
            $lock->release();
        }
    }

    private function record(Campaign $campaign, CampaignSyncRun $run, PlatformSnapshot $snapshot): void
    {
        $now = now();
        $isBaseline = ! $campaign->syncRuns()
            ->whereKeyNot($run->id)
            ->whereIn('status', [CampaignSyncRun::Succeeded, CampaignSyncRun::Partial])
            ->exists();

        $stored = $campaign->platformEntities()->get()
            ->keyBy(fn (CampaignPlatformEntity $entity): string => $entity->entity_type.'|'.$entity->external_id);

        $seen = [];
        $drifts = 0;

        foreach ($this->unique($snapshot->entities) as $key => $entity) {
            $seen[$key] = true;
            $existing = $stored->get($key);

            if ($existing === null) {
                $row = $campaign->platformEntities()->create([
                    ...$this->attributes($campaign, $entity),
                    'first_seen_at' => $now,
                    'last_seen_at' => $now,
                    'last_changed_at' => $isBaseline ? null : $now,
                ]);

                if (! $isBaseline) {
                    $drifts += $this->drift($run, $row, CampaignPlatformDrift::Added, null, null, $entity->comparable(), $now);
                }

                continue;
            }

            $changes = $this->differences($existing, $entity);
            $wasRemoved = $existing->removed_at !== null;

            if ($wasRemoved) {
                $drifts += $this->drift($run, $existing, CampaignPlatformDrift::Restored, null, null, null, $now);
            }

            foreach ($changes as $field => [$before, $after]) {
                $drifts += $this->drift($run, $existing, CampaignPlatformDrift::Changed, $field, $before, $after, $now);
            }

            $existing->update([
                ...$this->attributes($campaign, $entity),
                'last_seen_at' => $now,
                'removed_at' => null,
                'last_changed_at' => $changes !== [] || $wasRemoved ? $now : $existing->last_changed_at,
            ]);
        }

        foreach ($stored as $key => $existing) {
            if (isset($seen[$key]) || $existing->removed_at !== null || ! $snapshot->covers($existing->entity_type)) {
                continue;
            }

            $existing->update(['removed_at' => $now, 'last_changed_at' => $now]);
            $drifts += $this->drift($run, $existing, CampaignPlatformDrift::Removed, null, null, null, $now);
        }

        $run->update([
            'status' => $snapshot->complete() ? CampaignSyncRun::Succeeded : CampaignSyncRun::Partial,
            'complete' => $snapshot->complete(),
            'gaps' => $snapshot->gaps === [] ? null : $snapshot->gaps,
            'entity_count' => count($seen),
            'drift_count' => $drifts,
            'finished_at' => now(),
        ]);
    }

    /**
     * One entry per object; a platform listing the same id twice is read once.
     *
     * @param  list<PlatformEntity>  $entities
     * @return array<string, PlatformEntity>
     */
    private function unique(array $entities): array
    {
        $unique = [];

        foreach ($entities as $entity) {
            $unique[$entity->key()] = $entity;
        }

        return $unique;
    }

    /** @return array<string, mixed> */
    private function attributes(Campaign $campaign, PlatformEntity $entity): array
    {
        return [
            'platform' => $campaign->platform,
            'entity_type' => $entity->type,
            'external_id' => $entity->externalId,
            'parent_type' => $entity->parentType,
            'parent_external_id' => $entity->parentExternalId,
            'name' => $entity->name !== null ? Str::limit($entity->name, 250) : null,
            'status' => $entity->status !== null ? Str::limit($entity->status, 60, '') : null,
            'effective_status' => $entity->effectiveStatus !== null ? Str::limit($entity->effectiveStatus, 60, '') : null,
            'settings' => Canonical::sort($entity->settings),
            'fingerprint' => $entity->fingerprint(),
        ];
    }

    /**
     * Field-level differences between the stored row and a fresh read.
     *
     * @return array<string, array{0: mixed, 1: mixed}>
     */
    private function differences(CampaignPlatformEntity $existing, PlatformEntity $entity): array
    {
        if ($existing->fingerprint === $entity->fingerprint()) {
            return [];
        }

        $before = [
            'name' => $existing->name,
            'status' => $existing->status,
            'effective_status' => $existing->effective_status,
            'parent' => $existing->parent_external_id,
        ];
        $after = [
            'name' => $entity->name !== null ? Str::limit($entity->name, 250) : null,
            'status' => $entity->status,
            'effective_status' => $entity->effectiveStatus,
            'parent' => $entity->parentExternalId,
        ];

        $oldSettings = Canonical::sort((array) $existing->settings);
        $newSettings = Canonical::sort($entity->settings);

        foreach (array_unique([...array_keys($oldSettings), ...array_keys($newSettings)]) as $field) {
            $before['settings.'.$field] = $oldSettings[$field] ?? null;
            $after['settings.'.$field] = $newSettings[$field] ?? null;
        }

        $changes = [];

        foreach ($after as $field => $value) {
            if ($this->normalize($before[$field] ?? null) !== $this->normalize($value)) {
                $changes[$field] = [$before[$field] ?? null, $value];
            }
        }

        return $changes;
    }

    /** JSON round-trips turn 25.0 into 25; compare on the stored shape. */
    private function normalize(mixed $value): string
    {
        return (string) json_encode(is_array($value) ? Canonical::sort($value) : $value);
    }

    private function drift(CampaignSyncRun $run, CampaignPlatformEntity $entity, string $kind, ?string $field, mixed $before, mixed $after, Carbon $at): int
    {
        CampaignPlatformDrift::create([
            'campaign_id' => $run->campaign_id,
            'campaign_sync_run_id' => $run->id,
            'campaign_platform_entity_id' => $entity->id,
            'kind' => $kind,
            'field' => $field,
            'before' => $before,
            'after' => $after,
            'detected_at' => $at,
        ]);

        return 1;
    }
}
