<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\CampaignDuplicator;
use App\Models\Campaign;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\DB;
use Laravel\Ai\Contracts\ConversationStore;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Models\Conversation;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

class DuplicateCampaign implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly CampaignDuplicator $duplicator,
    ) {}

    public function description(): Stringable|string
    {
        return 'Duplicate a campaign into a new chat with a separate local draft containing its budget, ad sets, targeting, ad copy, and attached assets. '
            .'Use the focused campaign, or pass the local campaign ID of one owned by this user. '
            .'Nothing is sent to an ad platform. Return the new chat URL so the user can open and review the draft before any later publication.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'campaign_id' => $schema->integer()->description('Local campaign ID to copy. Omit to copy the campaign in focus.'),
            'name' => $schema->string()->description('Name for the new draft. Defaults to the original name followed by "(copy)".'),
        ];
    }

    public function handle(Request $request): Stringable|string
    {
        $owner = $this->workspace->owner();

        if ($owner === null) {
            return $this->json(['ok' => false, 'error' => 'Sign in before duplicating a campaign.']);
        }

        $arguments = $request->all();
        $source = isset($arguments['campaign_id'])
            ? Campaign::query()->where('user_id', $owner->getKey())->find((int) $arguments['campaign_id'])
            : $this->focused();

        if ($source === null || (string) $source->user_id !== (string) $owner->getKey()) {
            return $this->json(['ok' => false, 'error' => 'Choose a campaign owned by the signed-in user to duplicate.']);
        }

        $name = trim((string) ($arguments['name'] ?? ''));
        $name = $name !== '' ? $name : mb_substr($source->name, 0, 248).' (copy)';

        try {
            [$copy, $conversationId] = DB::transaction(function () use ($source, $owner, $name, $request): array {
                $conversationId = app(ConversationStore::class)->storeConversation(
                    Conversation::participantType($owner),
                    Conversation::participantKey($owner),
                    $name,
                );
                $copy = $this->duplicator->duplicate($source, $owner, $conversationId, $name);
                $destination = new Workspace($conversationId);
                $destination->ownedBy($owner);

                foreach ($copy->ads()->whereNotNull('asset_id')->with('asset')->get()->pluck('asset')->filter()->unique('id') as $asset) {
                    $destination->produced($asset, $request->toolCallId(), focus: false);
                }

                $destination->produced($copy, $request->toolCallId());

                foreach ($this->workspace->sourcesFor($source) as $field => $provenance) {
                    $destination->recordSource($copy, $field, $provenance);
                }

                return [$copy, $conversationId];
            });
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        return $this->json([
            'ok' => true,
            'source_campaign_id' => $source->getKey(),
            'campaign_id' => $copy->getKey(),
            'conversation' => $conversationId,
            'url' => route('chat.show', ['conversation' => $conversationId]),
            'name' => $copy->name,
            'platform' => $copy->platform,
            'status' => 'draft',
            'ad_sets' => $copy->adSets()->count(),
            'ads' => $copy->ads()->count(),
            'note' => 'Open the new chat to review its account, dates, targeting, budget, and assets before requesting publication.',
        ]);
    }
}
