<?php

namespace App\Campaigns;

use App\Agent\Workspace;
use App\Campaigns\Targeting\GoogleUserListSelections;
use App\Campaigns\Targeting\LinkedInAudienceSelections;
use App\Campaigns\Targeting\MetaAudienceSelections;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\CampaignAdSet;
use App\Models\Decision;
use Illuminate\Support\Facades\Auth;
use Laravel\Ai\Approvals\Approval;
use Laravel\Ai\Tools\Request;

class CampaignApprovalBinding
{
    public function __construct(
        private readonly Workspace $workspace,
        private readonly PendingChanges $pending,
        private readonly TargetingSelections $selections,
        private readonly SearchKeywordSelections $searchKeywords,
        private readonly GoogleUserListSelections $userLists,
        private readonly MetaAudienceSelections $metaAudiences,
        private readonly LinkedInAudienceSelections $linkedinAudiences,
    ) {}

    public function request(Request $request, ?Campaign $campaign, string $action, array $reviewedArguments = [], ?string $note = null): Approval
    {
        $callId = $request->toolCallId();

        if ($callId === null || $campaign === null) {
            return Approval::required('No campaign can be bound to this approval. Select a campaign and try again.');
        }

        $binding = Decision::query()->firstOrCreate(['approval_call_id' => $callId], [
            'origin' => 'agent',
            'action' => $action,
            'subject_type' => 'campaign',
            'subject_id' => (string) $campaign->id,
            'params' => [
                'fingerprint' => $this->fingerprint($campaign),
                'reviewed_arguments' => $reviewedArguments,
                'name' => $campaign->name,
                'platform' => $campaign->platform,
                'budget' => $campaign->budget,
                'countries' => $this->selections->countries($campaign),
                'selected_places' => $this->selections->reviewedCampaignPlaces($campaign),
                'google_location_presence' => $campaign->platform === 'google'
                    ? $this->selections->googlePresenceMode($campaign) : null,
                'google_search_keywords' => $campaign->platform === 'google'
                    && ($campaign->campaign_type ?: 'search') === 'search'
                        ? $this->searchKeywords->criteria($campaign) : null,
                'google_user_lists' => $campaign->platform === 'google'
                    ? $this->userLists->selected($campaign) : null,
                'meta_audiences' => $campaign->platform === 'meta'
                    ? $this->metaAudiences->selected($campaign) : null,
                'linkedin_segments' => $campaign->platform === 'linkedin'
                    ? $this->linkedinAudiences->selected($campaign) : null,
            ],
            'evidence' => [
                'user_id' => $this->userId(),
                'conversation_id' => $this->workspace->id(),
            ],
            'state' => 'proposed',
        ]);

        if ($binding->action !== $action
            || (string) ($binding->evidence['user_id'] ?? '') !== (string) $this->userId()
            || (string) ($binding->evidence['conversation_id'] ?? '') !== (string) $this->workspace->id()) {
            return Approval::required('This approval is no longer valid. Review the campaign again.');
        }

        $places = collect($binding->params['selected_places'] ?? [])
            ->map(fn (array $place): string => $place['kind'] === 'radius'
                ? $place['label']
                : sprintf('%s%s (%s ID %s)',
                    ($place['operation'] ?? 'include') === 'exclude' ? 'Excluded: ' : '',
                    $place['label'], ucfirst((string) $binding->params['platform']), $place['external_id'] ?? 'missing'))
            ->implode(', ');
        $keywords = collect($binding->params['google_search_keywords'] ?? [])
            ->map(static fn (array $keyword): string => sprintf('%s%s [%s]',
                $keyword['negative'] ? 'exclude ' : '',
                $keyword['text'],
                $keyword['match_type'],
            ))->implode(', ');
        $audiences = collect($binding->params['google_user_lists'] ?? [])
            ->map(static fn (array $list): string => sprintf('%s %s (%s)',
                $list['operation'], $list['name'], $list['resource_name'],
            ))->implode(', ');
        $metaAudiences = collect($binding->params['meta_audiences'] ?? [])
            ->map(static fn (array $audience): string => sprintf('%s %s (Meta ID %s, pixel %s)',
                $audience['operation'], $audience['name'], $audience['id'], $audience['pixel_id'],
            ))->implode(', ');
        $linkedinSegments = collect($binding->params['linkedin_segments'] ?? [])
            ->map(static fn (array $segment): string => sprintf('%s %s (%s)',
                $segment['operation'], $segment['name'], $segment['urn'],
            ))->implode(', ');

        $reason = sprintf(
            '%s campaign %s (#%s) on %s with budget %s. Selected countries: %s. Selected places/markets: %s. Google presence: %s. Search keywords: %s. Audience lists: %s. Meta website audiences: %s. LinkedIn retargeting segments: %s. Review its current details before approving.',
            str_replace('_', ' ', ucfirst($action)),
            $binding->params['name'],
            $binding->subject_id,
            ucfirst((string) $binding->params['platform']),
            $binding->params['budget'] ?? 'not set',
            implode(', ', $binding->params['countries'] ?? []) ?: 'none',
            $places ?: 'none',
            $binding->params['google_location_presence'] ?? 'not applicable',
            $keywords ?: 'none',
            $audiences ?: 'none',
            $metaAudiences ?: 'none',
            $linkedinSegments ?: 'none',
        );

        if (filled($note)) {
            $reason .= ' '.$note;
        }
        if ($action === 'delete_entity' && isset($binding->params['reviewed_arguments']['lifetime_delivery'])) {
            $delivery = collect($binding->params['reviewed_arguments']['lifetime_delivery'])
                ->map(fn (array $metrics, string|int $id): string => sprintf('%s: %.2f %s spent, %d impressions',
                    $id, $metrics['spend'], $metrics['currency'], $metrics['impressions']))->implode('; ');
            $reason .= ' Lifetime delivery: '.$delivery.'. Deletion cannot be undone. Delivered entities require a second confirmation; pausing preserves the work.';
        }

        return Approval::required($reason);
    }

    public function consume(Request $request, string $action, ?array $reviewedArguments = null): ?Campaign
    {
        $callId = $request->toolCallId();

        if ($callId === null) {
            return null;
        }

        $binding = Decision::query()->where('approval_call_id', $callId)->first();

        if ($binding === null || $binding->action !== $action || $binding->state !== 'proposed'
            || (string) ($binding->evidence['user_id'] ?? '') !== (string) $this->userId()
            || (string) ($binding->evidence['conversation_id'] ?? '') !== (string) $this->workspace->id()
            || $binding->created_at->addHour()->isPast()) {
            return null;
        }

        $campaign = Campaign::find($binding->subject_id);

        if ($reviewedArguments !== null && ($binding->params['reviewed_arguments'] ?? null) !== $reviewedArguments) {
            $binding->update(['state' => 'blocked', 'reason' => 'Reviewed arguments changed since approval was requested.']);

            return null;
        }

        if ($campaign === null || ! hash_equals((string) $binding->params['fingerprint'], $this->fingerprint($campaign))) {
            $binding->update(['state' => 'blocked', 'reason' => 'Campaign changed since approval was requested.']);

            return null;
        }

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

        return $claimed === 1 ? $campaign : null;
    }

    /**
     * @return array{campaign: Campaign, reviewed_arguments: array<string, mixed>}|null
     */
    public function consumeWithReviewedArguments(Request $request, string $action, array $expectedArguments): ?array
    {
        $callId = $request->toolCallId();
        if ($callId === null) {
            return null;
        }

        $binding = Decision::query()->where('approval_call_id', $callId)->first();
        $reviewedArguments = $binding?->params['reviewed_arguments'] ?? null;
        if (! is_array($reviewedArguments)) {
            return null;
        }

        foreach ($expectedArguments as $key => $expectedValue) {
            if (! array_key_exists($key, $reviewedArguments) || $reviewedArguments[$key] !== $expectedValue) {
                $binding->update(['state' => 'blocked', 'reason' => 'Reviewed arguments changed since approval was requested.']);

                return null;
            }
        }

        $campaign = $this->consume($request, $action, $reviewedArguments);

        return $campaign === null ? null : [
            'campaign' => $campaign,
            'reviewed_arguments' => $reviewedArguments,
        ];
    }

    private function userId(): string
    {
        return (string) (Auth::id() ?? $this->workspace->owner()?->getKey());
    }

    private function fingerprint(Campaign $campaign): string
    {
        return hash('sha256', json_encode([
            $campaign->getAttributes(),
            $campaign->adSets()->get()->map(fn (CampaignAdSet $adSet): array => $adSet->getAttributes())->all(),
            $this->pending->snapshot($campaign),
            $campaign->targetingSet()->value('revision'),
        ], JSON_THROW_ON_ERROR));
    }
}
