<?php

namespace App\Campaigns\Targeting;

use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\Decision;
use Illuminate\Support\Facades\Auth;
use Laravel\Ai\Approvals\Approval;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Throwable;

/** Bind a reviewed location change to one SDK tool call and provider snapshot. */
class PublishedLocationApprovalBinding
{
    private const ACTION = 'edit_published_location';

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

    public function request(Request $request, ?Campaign $campaign): Approval
    {
        $callId = $request->toolCallId();

        if ($callId === null || $campaign === null || Auth::id() === null
            || (string) $campaign->user_id !== (string) Auth::id() || $this->workspace->id() === null) {
            return Approval::required('No owned campaign can be bound to this location edit. Review the campaign again.');
        }

        try {
            [$operation, $mappingId, $revision, $replacedMappingId] = $this->arguments($request);
            $plan = $this->preview($campaign, $operation, $mappingId, $revision, $replacedMappingId);
        } catch (RuntimeException $exception) {
            return Approval::required('This location edit cannot be approved: '.$exception->getMessage());
        } catch (Throwable $exception) {
            report($exception);

            return Approval::required('This location edit could not be verified. Review it again.');
        }

        $binding = Decision::query()->firstOrCreate(['approval_call_id' => $callId], [
            'origin' => 'agent',
            'action' => self::ACTION,
            'subject_type' => 'campaign',
            'subject_id' => (string) $campaign->getKey(),
            'params' => ['plan' => $plan],
            'evidence' => [
                'user_id' => (string) Auth::id(),
                'conversation_id' => $this->workspace->id(),
            ],
            'state' => 'proposed',
        ]);

        if (! $this->belongsToCurrentRequest($binding, $campaign) || $binding->state !== 'proposed'
            || ($binding->params['plan']['fingerprint'] ?? null) !== $plan['fingerprint']) {
            return Approval::required('This location approval changed or belongs to another request. Review it again.');
        }

        return Approval::required(sprintf(
            '%s %s (%s ID %s) on %s campaign %s (#%s), account %s. Current locations: %s. Proposed locations: %s. Nothing changes until you approve.',
            ucfirst($operation).($operation === 'replace' ? ' '.$plan['replaced_place']['label'].' with' : ''),
            $plan['place']['label'],
            ucfirst((string) $plan['platform']),
            $plan['place']['external_id'],
            ucfirst((string) $plan['platform']),
            $campaign->name,
            $campaign->getKey(),
            $plan['account_id'],
            json_encode($plan['before'], JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR),
            json_encode($plan['after'], JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR),
        ));
    }

    /** @return array{campaign: Campaign, plan: array<string, mixed>, decision: Decision}|null */
    public function consume(Request $request): ?array
    {
        $callId = $request->toolCallId();

        if ($callId === null || Auth::id() === null || $this->workspace->id() === null) {
            return null;
        }

        $binding = Decision::query()->where('approval_call_id', $callId)->first();
        $campaign = $binding === null ? null : Campaign::find($binding->subject_id);

        if ($binding === null || $campaign === null || ! $this->belongsToCurrentRequest($binding, $campaign)
            || $binding->state !== 'proposed' || $binding->created_at->addHour()->isPast()) {
            return null;
        }

        $savedPlan = $binding->params['plan'] ?? null;

        try {
            [$operation, $mappingId, $revision, $replacedMappingId] = $this->arguments($request);

            if (! is_array($savedPlan) || data_get($savedPlan, 'operation') !== $operation
                || (int) data_get($savedPlan, 'place.mapping_id') !== $mappingId
                || (int) data_get($savedPlan, 'revision') !== $revision
                || (int) data_get($savedPlan, 'replaced_place.mapping_id') !== ($replacedMappingId ?? 0)) {
                throw new RuntimeException('Approved location arguments changed.');
            }

            $currentPlan = $this->preview($campaign, $operation, $mappingId, $revision, $replacedMappingId);

            if (! hash_equals((string) $savedPlan['fingerprint'], $currentPlan['fingerprint'])) {
                throw new RuntimeException('Campaign, mapping, or provider locations changed since review.');
            }
        } catch (Throwable $exception) {
            $binding->update(['state' => 'blocked', 'reason' => $exception->getMessage()]);

            return null;
        }

        $claimed = Decision::query()->whereKey($binding->getKey())->where('state', 'proposed')
            ->update(['state' => 'consumed']);

        return $claimed === 1
            ? ['campaign' => $campaign, 'plan' => $currentPlan, 'decision' => $binding->fresh()]
            : null;
    }

    private function belongsToCurrentRequest(Decision $binding, Campaign $campaign): bool
    {
        return $binding->action === self::ACTION
            && $binding->subject_type === 'campaign'
            && (string) $binding->subject_id === (string) $campaign->getKey()
            && (string) $campaign->user_id === (string) Auth::id()
            && (string) ($binding->evidence['user_id'] ?? '') === (string) Auth::id()
            && (string) ($binding->evidence['conversation_id'] ?? '') === (string) $this->workspace->id();
    }

    /** @return array{string, int, int, int|null} */
    private function arguments(Request $request): array
    {
        $arguments = $request->all();
        $operation = (string) ($arguments['operation'] ?? '');
        $mappingId = $arguments['mapping_id'] ?? null;
        $revision = $arguments['expected_revision'] ?? null;
        $replacedMappingId = $arguments['replace_mapping_id'] ?? null;

        if (! in_array($operation, ['add', 'remove', 'replace'], true)
            || ! $this->integerArgument($mappingId, false)
            || ! $this->integerArgument($revision, true)
            || ($operation === 'replace' && ! $this->integerArgument($replacedMappingId, false))
            || ($operation !== 'replace' && $replacedMappingId !== null)) {
            throw new RuntimeException('Provide an add/remove/replace operation, mapping ID, targeting revision, and an old mapping ID for replacement.');
        }

        return [$operation, (int) $mappingId, (int) $revision, $replacedMappingId === null ? null : (int) $replacedMappingId];
    }

    /** @return array<string, mixed> */
    private function preview(Campaign $campaign, string $operation, int $mappingId, int $revision, ?int $replacedMappingId): array
    {
        return $replacedMappingId === null
            ? $this->planner->preview($campaign, $operation, $mappingId, $revision)
            : $this->planner->preview($campaign, $operation, $mappingId, $revision, $replacedMappingId);
    }

    private function integerArgument(mixed $value, bool $allowZero): bool
    {
        return (is_int($value) && ($allowZero ? $value >= 0 : $value > 0))
            || (is_string($value) && ctype_digit($value) && ($allowZero || (int) $value > 0));
    }
}
