<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\WhaleAdopsReader;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Support\CurrencyMinorUnits;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

/**
 * Spend, bid, and budget for campaigns that are still active or paused.
 *
 * list_campaigns names a campaign and list_campaign_structure names its ad
 * sets. Neither returns what those objects have spent, or the bid sitting on
 * an ad set. Both live on Meta, and a paused campaign keeps them: pausing
 * stops delivery, it does not zero the budget or erase the spend.
 *
 * Amounts Meta stores as minor units are converted here. Insights spend is
 * already in major units and is left alone.
 */
class ReadDelivery implements Tool
{
    use ActsOnFocusedCampaign;

    /** One more than we show, so a full page can be told apart from the last page. */
    private const CAMPAIGN_PAGE = 26;

    private const AD_SET_PAGE = 51;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Meta $meta,
        private readonly WhaleAdopsReader $whale,
    ) {}

    public function description(): Stringable|string
    {
        return 'Read spend, bid, and budget for one active or paused Meta campaign and its ad sets. '
            .'Those three are read from the warehouse when it has all of them, and from Meta when it does not. '
            .'If the user has not given a campaign id or name, ask for one and wait. Do not call this '
            .'yet, and do not use the campaign in focus. A name is resolved with list_campaigns, then '
            .'passed here as campaign_id. all_campaigns is only for a request that names every active '
            .'and paused campaign on the account. Spend is lifetime spend. A null spend means no figure '
            .'was stored, not that the spend is zero. Budget and bid are what is set now, in '
            .'the account currency. A Meta read of one campaign also includes pacing, schedule, dayparting, targeting, '
            .'placements, devices, the optimization goal, the conversion event, and the locked fields. '
            .'Archived and deleted campaigns are omitted.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_account_id' => $schema->string()
                ->description('The ad account, for example act_123456789. Defaults to the account of the campaign in focus.'),
            'campaign_id' => $schema->string()
                ->description('The Meta campaign id to read, including its ad sets. A name is not accepted: resolve it with list_campaigns first. Required unless the user asked for every campaign on the account.'),
            'all_campaigns' => $schema->boolean()
                ->description('True only when the user asks for every active and paused campaign on the account. Otherwise ask for a campaign id or name and do not call this tool.'),
        ];
    }

    public function handle(Request $request): Stringable|string
    {
        $arguments = $request->all();
        $focused = $this->focused();
        $adAccountId = trim((string) ($arguments['ad_account_id'] ?? ''));

        if ($adAccountId === '' && $focused !== null && $focused->platform === 'meta') {
            $adAccountId = (string) $focused->ad_account_id;
        }

        if ($adAccountId === '') {
            return $this->json([
                'ok' => false,
                'error' => 'An ad account id is needed. Call list_ad_accounts first.',
            ]);
        }

        $campaignId = preg_replace('/\D/', '', (string) ($arguments['campaign_id'] ?? '')) ?? '';

        if ($campaignId === '' && ! filter_var($arguments['all_campaigns'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
            return $this->json([
                'ok' => false,
                'error' => 'A campaign id or name is needed before spend, bid, and budget can be read.',
                'note' => 'Ask for the campaign id or name and wait. Do not guess the campaign in focus. '
                    .'If they give a name, call list_campaigns with that name, then call this again with the matching campaign id. '
                    .'If more than one matches, ask which one. If they ask for every active and paused campaign on the account, '
                    .'call this again with all_campaigns true.',
            ]);
        }

        if ($campaignId !== '') {
            $stored = $this->fromWarehouse($adAccountId, $campaignId);

            if ($stored !== null) {
                return $this->json($stored);
            }
        }

        try {
            $currency = (string) ($this->meta->adAccount($adAccountId, fresh: true)['currency'] ?? '');

            if ($campaignId !== '') {
                return $this->json($this->oneCampaign($adAccountId, $campaignId, $currency));
            }

            return $this->json($this->account($adAccountId, $currency));
        } catch (MetaException $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'This is a platform error. Do not invent spend, bid, or budget.',
            ]);
        }
    }

    /**
     * Warehouse figures when spend, bid, and budget are all stored. Null sends the read to Meta.
     *
     * @return array<string, mixed>|null
     */
    private function fromWarehouse(string $adAccountId, string $campaignId): ?array
    {
        $stored = $this->whale->deliveryFigures('meta', $campaignId);

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

        $owner = preg_replace('/^act_/', '', (string) ($stored['account_id'] ?? '')) ?? '';
        $account = preg_replace('/^act_/', '', $adAccountId) ?? '';

        if ($owner !== '' && $owner !== $account) {
            return [
                'ok' => false,
                'error' => "Campaign {$campaignId} is not on {$this->accountId($adAccountId)}.",
            ];
        }

        $effective = strtoupper((string) ($stored['effective_status'] ?? $stored['status'] ?? ''));

        if (in_array($effective, ['ARCHIVED', 'DELETED'], true)) {
            return [
                'ok' => false,
                'error' => "Campaign {$campaignId} is {$effective}, so it is not in the active and paused delivery read.",
            ];
        }

        $currency = (string) ($stored['currency'] ?? '');

        if ($currency === '') {
            $focused = $this->focused();
            $currency = $focused !== null && (string) $focused->external_campaign_id === $campaignId
                ? (string) $focused->currency
                : '';
        }

        $daily = $stored['daily_budget'];
        $lifetime = $stored['lifetime_budget'];

        return [
            'ok' => true,
            'source' => 'whale',
            'ad_account_id' => $this->accountId($adAccountId),
            'currency' => $currency,
            'spend_period' => 'lifetime',
            'campaigns' => [[
                'id' => $campaignId,
                'name' => $stored['name'],
                'status' => $stored['status'],
                'effective_status' => $stored['effective_status'],
                'budget_level' => $daily !== null || $lifetime !== null ? 'campaign' : 'ad_set',
                'daily_budget' => $daily,
                'lifetime_budget' => $lifetime,
                'bid_strategy' => $stored['bid_strategy'],
                'bid_amount' => $stored['bid_amount'],
                'spend' => $stored['spend'],
                'ad_sets' => $stored['ad_sets'],
            ]],
            'truncated' => false,
            'note' => 'Spend, bid, and budget were read from the warehouse. Spend is the sum of stored daily spend'
                .($currency !== '' ? ', in '.$currency : '').'. A spend of zero is zero. Meta was not called. '
                .'An ad set spend of null means no ad set spend row was stored. Do not read that as zero. '
                .'Pacing, schedule, targeting, placements, and devices are not in this read.',
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function account(string $adAccountId, string $currency): array
    {
        $rows = $this->meta->deliveryCampaigns($adAccountId, self::CAMPAIGN_PAGE);
        $rows = $this->onlyActiveOrPaused($rows);
        $truncated = count($rows) > 25;
        $rows = array_slice($rows, 0, 25);
        $ids = array_values(array_filter(array_map(
            static fn (array $row): string => (string) ($row['id'] ?? ''),
            $rows,
        )));
        $spend = $ids === [] ? [] : $this->meta->lifetimeSpend($this->accountId($adAccountId), 'campaign', $adAccountId, $ids);

        return [
            'ok' => true,
            'ad_account_id' => $this->accountId($adAccountId),
            'currency' => $currency,
            'campaigns' => array_map(
                fn (array $row): array => $this->campaignRow($row, $currency, $spend[(string) ($row['id'] ?? '')] ?? null),
                $rows,
            ),
            'spend_period' => 'lifetime',
            'truncated' => $truncated,
            'note' => 'Active and paused campaigns only. Spend is lifetime spend, in '.$currency.'. '
                .'Null spend means Meta returned no lifetime figure. Do not read that as zero. '
                .'Budget is in '.$currency.' too. Bid amounts, schedule, and targeting live on the ad sets: pass campaign_id to read them. '
                .($truncated ? 'More campaigns exist than are shown.' : 'This is the full list.'),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function oneCampaign(string $adAccountId, string $campaignId, string $currency): array
    {
        $campaign = $this->meta->campaign($campaignId, $adAccountId, fresh: true);
        $owner = preg_replace('/^act_/', '', (string) ($campaign['account_id'] ?? '')) ?? '';
        $account = preg_replace('/^act_/', '', $adAccountId) ?? '';

        if ($owner !== '' && $owner !== $account) {
            return [
                'ok' => false,
                'error' => "Campaign {$campaignId} is not on {$this->accountId($adAccountId)}.",
            ];
        }

        $effective = strtoupper((string) ($campaign['effective_status'] ?? $campaign['status'] ?? ''));

        if (in_array($effective, ['ARCHIVED', 'DELETED'], true)) {
            return [
                'ok' => false,
                'error' => "Campaign {$campaignId} is {$effective}, so it is not in the active and paused delivery read.",
            ];
        }

        $adSets = $this->onlyRunningAdSets($this->meta->deliveryAdSets($campaignId, $adAccountId, self::AD_SET_PAGE));
        $truncated = count($adSets) > 50;
        $adSets = array_slice($adSets, 0, 50);
        $adSetSpend = $this->meta->lifetimeSpend($campaignId, 'adset', $adAccountId);
        $campaignSpend = $this->meta->lifetimeSpend($campaignId, 'campaign', $adAccountId);

        $row = $this->campaignRow($campaign, $currency, $campaignSpend[$campaignId] ?? null);
        $row['start_time'] = $campaign['start_time'] ?? null;
        $row['end_time'] = $campaign['stop_time'] ?? null;
        $row['ad_sets'] = array_map(
            fn (array $adSet): array => $this->adSetRow($adSet, $currency, $adSetSpend[(string) ($adSet['id'] ?? '')] ?? null),
            $adSets,
        );

        return [
            'ok' => true,
            'ad_account_id' => $this->accountId($adAccountId),
            'currency' => $currency,
            'spend_period' => 'lifetime',
            'campaigns' => [$row],
            'truncated' => $truncated,
            'note' => 'Spend is lifetime spend, in '.$currency.', including while paused. '
                .'Null spend means Meta returned no lifetime figure. Do not read that as zero. '
                .'Budget, bid, and spend caps are what is set now. A null ad set budget means the campaign holds the budget. '
                .'locked_fields cannot be changed on an ad set that already exists.',
        ];
    }

    /**
     * @param  array<string, mixed>  $row
     * @return array<string, mixed>
     */
    private function campaignRow(array $row, string $currency, ?float $spend): array
    {
        $daily = $this->money($row['daily_budget'] ?? null, $currency);
        $lifetime = $this->money($row['lifetime_budget'] ?? null, $currency);

        return [
            'id' => $row['id'] ?? null,
            'name' => $row['name'] ?? null,
            'status' => $row['status'] ?? null,
            'effective_status' => $row['effective_status'] ?? null,
            'budget_level' => $daily !== null || $lifetime !== null ? 'campaign' : 'ad_set',
            'daily_budget' => $daily,
            'lifetime_budget' => $lifetime,
            'bid_strategy' => $row['bid_strategy'] ?? null,
            'spend' => $spend,
        ];
    }

    /**
     * @param  array<string, mixed>  $row
     * @return array<string, mixed>
     */
    private function adSetRow(array $row, string $currency, ?float $spend): array
    {
        $constraints = is_array($row['bid_constraints'] ?? null) ? $row['bid_constraints'] : [];
        $floor = $constraints['roas_average_floor'] ?? null;
        $promoted = is_array($row['promoted_object'] ?? null) ? $row['promoted_object'] : null;
        $targeting = is_array($row['targeting'] ?? null) ? $row['targeting'] : [];

        return [
            'id' => $row['id'] ?? null,
            'name' => $row['name'] ?? null,
            'status' => $row['status'] ?? null,
            'effective_status' => $row['effective_status'] ?? null,
            'daily_budget' => $this->money($row['daily_budget'] ?? null, $currency),
            'lifetime_budget' => $this->money($row['lifetime_budget'] ?? null, $currency),
            'bid_strategy' => $row['bid_strategy'] ?? null,
            'bid_amount' => $this->money($row['bid_amount'] ?? null, $currency),
            'roas_average_floor' => is_numeric($floor) ? ((float) $floor) / 10000 : null,
            'pacing_type' => $row['pacing_type'] ?? null,
            'daily_min_spend_target' => $this->money($row['daily_min_spend_target'] ?? null, $currency),
            'daily_spend_cap' => $this->money($row['daily_spend_cap'] ?? null, $currency),
            'lifetime_min_spend_target' => $this->money($row['lifetime_min_spend_target'] ?? null, $currency),
            'lifetime_spend_cap' => $this->money($row['lifetime_spend_cap'] ?? null, $currency),
            'start_time' => $row['start_time'] ?? null,
            'end_time' => $row['end_time'] ?? null,
            'adset_schedule' => $row['adset_schedule'] ?? null,
            'targeting' => $this->audience($targeting),
            'placements' => $this->placements($targeting),
            'devices' => $this->devices($targeting),
            'optimization_goal' => $row['optimization_goal'] ?? null,
            'conversion_event' => $promoted['custom_event_type'] ?? null,
            'promoted_object' => $promoted,
            'destination_type' => $row['destination_type'] ?? null,
            'billing_event' => $row['billing_event'] ?? null,
            'attribution_spec' => $row['attribution_spec'] ?? null,
            'is_dynamic_creative' => $row['is_dynamic_creative'] ?? null,
            'locked_fields' => ['optimization_goal', 'destination_type', 'billing_event', 'attribution_spec', 'is_dynamic_creative'],
            'spend' => $spend,
        ];
    }

    /**
     * @param  array<string, mixed>  $targeting
     * @return array<string, mixed>
     */
    private function audience(array $targeting): array
    {
        $automation = is_array($targeting['targeting_automation'] ?? null) ? $targeting['targeting_automation'] : [];

        return [
            'geo_locations' => $targeting['geo_locations'] ?? null,
            'excluded_geo_locations' => $targeting['excluded_geo_locations'] ?? null,
            'age_min' => $targeting['age_min'] ?? null,
            'age_max' => $targeting['age_max'] ?? null,
            'genders' => $targeting['genders'] ?? null,
            'locales' => $targeting['locales'] ?? null,
            'custom_audiences' => $targeting['custom_audiences'] ?? null,
            'excluded_custom_audiences' => $targeting['excluded_custom_audiences'] ?? null,
            'flexible_spec' => $targeting['flexible_spec'] ?? null,
            'exclusions' => $targeting['exclusions'] ?? null,
            'advantage_audience' => $automation['advantage_audience'] ?? null,
            'targeting_relaxation_types' => $targeting['targeting_relaxation_types'] ?? null,
        ];
    }

    /**
     * @param  array<string, mixed>  $targeting
     * @return array<string, mixed>
     */
    private function placements(array $targeting): array
    {
        return [
            'publisher_platforms' => $targeting['publisher_platforms'] ?? null,
            'facebook_positions' => $targeting['facebook_positions'] ?? null,
            'instagram_positions' => $targeting['instagram_positions'] ?? null,
            'audience_network_positions' => $targeting['audience_network_positions'] ?? null,
            'messenger_positions' => $targeting['messenger_positions'] ?? null,
            'threads_positions' => $targeting['threads_positions'] ?? null,
        ];
    }

    /**
     * @param  array<string, mixed>  $targeting
     * @return array<string, mixed>
     */
    private function devices(array $targeting): array
    {
        return [
            'device_platforms' => $targeting['device_platforms'] ?? null,
            'user_os' => $targeting['user_os'] ?? null,
            'user_device' => $targeting['user_device'] ?? null,
            'excluded_user_device' => $targeting['excluded_user_device'] ?? null,
            'wireless_carrier' => $targeting['wireless_carrier'] ?? null,
        ];
    }

    /**
     * @param  list<array<string, mixed>>  $rows
     * @return list<array<string, mixed>>
     */
    private function onlyActiveOrPaused(array $rows): array
    {
        return array_values(array_filter($rows, function (array $row): bool {
            $effective = strtoupper((string) ($row['effective_status'] ?? $row['status'] ?? ''));

            return in_array($effective, ['ACTIVE', 'PAUSED'], true);
        }));
    }

    /**
     * @param  list<array<string, mixed>>  $rows
     * @return list<array<string, mixed>>
     */
    private function onlyRunningAdSets(array $rows): array
    {
        return array_values(array_filter($rows, function (array $row): bool {
            $status = strtoupper((string) ($row['status'] ?? ''));

            return $status === '' || in_array($status, ['ACTIVE', 'PAUSED'], true);
        }));
    }

    private function money(mixed $minor, string $currency): ?float
    {
        if ($minor === null || $minor === '' || ! is_numeric($minor)) {
            return null;
        }

        return CurrencyMinorUnits::toMajor((int) $minor, $currency);
    }

    private function accountId(string $adAccountId): string
    {
        return str_starts_with($adAccountId, 'act_') ? $adAccountId : 'act_'.$adAccountId;
    }
}
