<?php

namespace App\Livewire\CampaignManager;

use App\Campaigns\Manager\CampaignSynchronizer;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\ManagedCampaigns;
use App\Models\Campaign;
use App\Models\CampaignEntityEdit;
use App\Models\CampaignPlatformDrift;
use App\Models\CampaignPlatformEntity;
use App\Models\CampaignSyncRun;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\RateLimiter;
use InvalidArgumentException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Component;
use RuntimeException;

/**
 * One campaign as its platform last reported it, with what changed since.
 *
 * Refreshing reads the platform and records the result; nothing here writes
 * to a platform. Changes are made one object at a time in EditEntity.
 */
#[Layout('layouts.mb', ['pageTitle' => 'Campaign manager'])]
class Show extends Component
{
    #[Locked]
    public int $campaignId;

    public ?string $notice = null;

    public ?string $problem = null;

    /** @var array{spend: float, impressions: int, read_at: string}|null */
    #[Locked]
    public ?array $delivery = null;

    public function mount(Campaign $campaign): void
    {
        $this->campaignId = $this->owned($campaign->id)->id;
    }

    /** Called once the page has rendered, so an old snapshot is renewed without holding up the first paint. */
    public function refreshIfStale(): void
    {
        $campaign = $this->owned($this->campaignId);
        $last = $campaign->latestSuccessfulSyncRun;

        if ($last !== null && $last->started_at->gt(now()->subMinutes($this->staleAfter()))) {
            return;
        }

        if ($campaign->latestSyncRun?->status === CampaignSyncRun::Running) {
            return;
        }

        $this->read($campaign, 'open');
    }

    public function refresh(): void
    {
        $campaign = $this->owned($this->campaignId);
        $key = sprintf('campaign-manager:refresh:%d:%d', auth()->id(), $campaign->id);

        if (RateLimiter::tooManyAttempts($key, max(1, (int) config('campaign-manager.refreshes_per_minute', 4)))) {
            $this->notice = null;
            $this->problem = sprintf('Refreshed too often. Try again in %d seconds.', RateLimiter::availableIn($key));

            return;
        }

        RateLimiter::hit($key, 60);

        $this->read($campaign, 'manual');
    }

    public function loadDelivery(EditCapabilities $capabilities): void
    {
        $campaign = $this->owned($this->campaignId);
        $key = sprintf('campaign-manager:delivery:%d:%d', auth()->id(), $campaign->id);
        if (RateLimiter::tooManyAttempts($key, 4)) {
            $this->problem = sprintf('Delivery was read too often. Try again in %d seconds.', RateLimiter::availableIn($key));

            return;
        }

        RateLimiter::hit($key, 60);
        $entity = $campaign->platformEntities()->where('entity_type', 'campaign')->whereNull('removed_at')->first();
        if ($entity === null) {
            $this->problem = 'Read the campaign structure before retrieving its delivery details.';

            return;
        }

        $this->problem = null;
        $this->delivery = null;
        try {
            $seen = $capabilities->writer($campaign->platform)->delivery($campaign, $entity, sprintf('User#%d campaign manager delivery', auth()->id()));
            $this->delivery = [...$seen, 'read_at' => now()->toIso8601String()];
        } catch (InvalidArgumentException|RuntimeException $exception) {
            $this->problem = 'Delivery details could not be retrieved: '.$exception->getMessage();
        }
    }

    public function render(): View
    {
        $campaign = $this->owned($this->campaignId)->load(['latestSyncRun', 'latestSuccessfulSyncRun']);

        $entities = $campaign->platformEntities()
            ->orderByRaw('removed_at is not null')
            ->orderBy('id')
            ->get()
            ->each->setRelation('campaign', $campaign);

        return view('livewire.campaign-manager.show', [
            'campaign' => $campaign,
            'roots' => $this->roots($entities),
            'children' => $entities->groupBy(fn (CampaignPlatformEntity $entity): string => $entity->parent_type.'|'.$entity->parent_external_id),
            'entityCount' => $entities->whereNull('removed_at')->count(),
            'typeCounts' => $entities->whereNull('removed_at')->countBy('entity_type'),
            'recentDriftCount' => $campaign->platformDrifts()->where('detected_at', '>=', now()->subDays(7))->count(),
            'drifts' => $drifts = $campaign->platformDrifts()->with(['entity', 'run'])->latest('detected_at')->latest('id')->limit(50)->get()
                ->each(fn (CampaignPlatformDrift $drift) => $drift->entity?->setRelation('campaign', $campaign)),
            'ownDrifts' => $this->ownDrifts($drifts, $edits = $campaign->entityEdits()->with(['entity', 'user'])->latest('id')->limit(20)->get()
                ->each(fn (CampaignEntityEdit $edit) => $edit->entity?->setRelation('campaign', $campaign))),
            'edits' => $edits->where('state', '!=', CampaignEntityEdit::Cancelled)->take(10),
            'capabilities' => app(EditCapabilities::class),
            'runs' => $campaign->syncRuns()->latest('id')->limit(10)->get(),
            'staleAfter' => $this->staleAfter(),
        ])->layoutData(['pageTitle' => 'Campaign manager - '.$campaign->name]);
    }

    private function read(Campaign $campaign, string $trigger): void
    {
        $this->notice = null;
        $this->problem = null;

        try {
            $run = app(CampaignSynchronizer::class)->sync($campaign, $trigger, sprintf('User#%d campaign manager', auth()->id()));
        } catch (InvalidArgumentException|RuntimeException $exception) {
            $this->problem = $exception->getMessage();

            return;
        }

        match ($run->status) {
            CampaignSyncRun::Failed => $this->problem = 'The platform could not be read: '.$run->error.' What is shown is the last successful read.',
            CampaignSyncRun::Partial => $this->notice = 'Read, but not everything could be covered. Objects outside what was read are kept as they were.',
            default => $this->notice = $run->drift_count > 0
                ? sprintf('Read just now. %d change(s) since the previous read.', $run->drift_count)
                : 'Read just now. Nothing changed since the previous read.',
        };
    }

    /**
     * The top of the tree: objects with no parent, or whose parent was not read.
     *
     * @param  Collection<int, CampaignPlatformEntity>  $entities
     * @return Collection<int, CampaignPlatformEntity>
     */
    private function roots(Collection $entities): Collection
    {
        $known = $entities->mapWithKeys(fn (CampaignPlatformEntity $entity): array => [$entity->entity_type.'|'.$entity->external_id => true]);

        return $entities->filter(fn (CampaignPlatformEntity $entity): bool => $entity->parent_external_id === null
            || ! $known->has($entity->parent_type.'|'.$entity->parent_external_id))->values();
    }

    /**
     * Drift ids that are the read-back of a change confirmed here, so they are
     * not mistaken for someone editing in the platform's own UI.
     *
     * @param  Collection<int, CampaignPlatformDrift>  $drifts
     * @param  Collection<int, CampaignEntityEdit>  $edits
     * @return array<int, true>
     */
    private function ownDrifts(Collection $drifts, Collection $edits): array
    {
        $applied = $edits->where('state', CampaignEntityEdit::Applied);

        return $drifts
            ->filter(fn (CampaignPlatformDrift $drift): bool => $drift->run?->trigger === 'readback'
                && $applied->contains(fn (CampaignEntityEdit $edit): bool => EditCapabilities::matchesDrift($edit, $drift)))
            ->mapWithKeys(fn (CampaignPlatformDrift $drift): array => [$drift->id => true])
            ->all();
    }

    /** Only the owner's own published, readable campaigns; everything else is not found. */
    private function owned(int $campaignId): Campaign
    {
        return ManagedCampaigns::query()
            ->where('user_id', auth()->id())
            ->findOrFail($campaignId);
    }

    private function staleAfter(): int
    {
        return max(1, (int) config('campaign-manager.stale_after_minutes', 60));
    }
}
