<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInUrn;
use App\Services\Meta\AdCreativeCopy;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Support\Actor;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

/**
 * What a campaign is actually made of: its ad sets and its ads, by id and name.
 *
 * Nothing could answer this. list_campaigns gives one line per campaign on an
 * account; open_campaign adopts one and reports a *count* of its other ad sets
 * and nothing else; review_published_location reads live ad sets but surfaces
 * only their geo targeting. The ids and names of the ad sets and ads under a
 * campaign reached the chat in exactly one place - an error branch in add_ads -
 * so a buyer could not ask what was in their campaign, and the model could not
 * name a thing in order to do anything to it.
 *
 * Read from the platform rather than from our own rows, for two reasons. Ad
 * sets are imported on adoption but ads are not imported at all, so local rows
 * cannot answer for a campaign this product did not build. And the point of
 * asking is to act afterwards, which needs the id the platform will accept and
 * the status it currently holds, not the one we last wrote down.
 *
 * Google was refused by name here until the read behind it existed. It now
 * does - GoogleAdsService::readCampaignStructure - so a Google campaign answers
 * in its own vocabulary rather than Meta's: ad groups, not ad sets, and asset
 * groups for Performance Max, which keeps its creative there and has no ad
 * groups to find. The shapes are deliberately not forced into one, because
 * telling a buyer their Performance Max campaign has "two ad sets" would be a
 * wrong answer dressed as a consistent one.
 *
 * Two reads on Meta, two or three on Google, on a request a person made. Not
 * something to call per turn.
 */
class ListCampaignStructure implements Tool
{
    use ActsOnFocusedCampaign;

    /** Enough to work with, and a bound on what one answer can cost. */
    private const MOST_SHOWN = 50;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Meta $meta,
        private readonly GoogleAdsService $google,
        private readonly Actor $actor,
        private readonly ?LinkedIn $linkedin = null,
    ) {}

    public function description(): Stringable|string
    {
        return 'List what a published campaign is made of: its ad sets and ads on Meta, its ad '
            .'groups, ads and Performance Max asset groups on Google, or its campaign group and '
            .'sponsored creatives on LinkedIn, with their ids, names and current statuses, and a '
            .'count of each. LinkedIn pages with a cursor. Use it whenever the user asks what is '
            .'in a campaign, how many ad sets, ad groups or ads it has, or names something they '
            .'want paused, restarted, edited or removed - you need the id from here first. Reads '
            .'the platform, so it reflects changes made in Ads Manager or the Google Ads UI. '
            .'Makes no platform changes. For LinkedIn it refreshes the local campaign status '
            .'cache and timestamp.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'page_token' => $schema->string()->description('LinkedIn creative pagination token returned by the previous result.'),
            'campaign_id' => $schema->string()
                ->description('The platform campaign id to inspect. Defaults to the campaign in focus.'),
            'ad_set_id' => $schema->string()
                ->description('Only list the ads under this one ad set (Meta) or ad group (Google), '
                    .'instead of every ad in the campaign.'),
        ];
    }

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

        if ($campaignId === '') {
            return $this->json([
                'ok' => false,
                'error' => $campaign === null
                    ? 'No campaign is in focus, so there is nothing to list. Ask which campaign they mean, or use list_campaigns to find it.'
                    : 'This campaign has not been published yet, so it has no ad sets or ads on '.ucfirst((string) $campaign->platform).' to list.',
            ]);
        }

        if ($campaign !== null && $campaign->platform === 'linkedin') {
            if (LinkedInUrn::numericId($campaignId) !== LinkedInUrn::numericId((string) $campaign->external_campaign_id)) {
                return $this->json(['ok' => false, 'error' => 'Open the requested campaign first. It is not the campaign in focus.']);
            }

            $live = null;
            $group = null;
            try {
                $linkedin = ($this->linkedin ?? app(LinkedIn::class))->on($campaign->id, $this->actor->describe());
                $live = $linkedin->campaign((string) $campaign->ad_account_id, $campaignId);
                if (blank($live['campaignGroup'] ?? null)) {
                    return $this->json(['ok' => false, 'campaign' => $live,
                        'error' => 'LinkedIn returned this campaign without a campaignGroup relationship. The group and creative structure cannot be verified.']);
                }
                $group = $linkedin->campaignGroup((string) $campaign->ad_account_id, (string) $live['campaignGroup']);
                $creatives = $linkedin->creatives((string) $campaign->ad_account_id, $campaignId, $arguments['page_token'] ?? null);
                foreach ($creatives['elements'] as $creative) {
                    if (LinkedInUrn::numericId((string) ($creative['campaign'] ?? '')) !== LinkedInUrn::numericId($campaignId)) {
                        throw new RuntimeException('LinkedIn returned a creative outside this campaign.');
                    }
                }
                $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_state' => [
                    'campaign_status' => $live['status'] ?? null, 'group_status' => $group['status'] ?? null,
                    'serving_statuses' => $live['servingStatuses'] ?? [], 'refreshed_at' => now()->toIso8601String(),
                ]]]);

                return $this->json(['ok' => true, 'platform' => 'linkedin', 'campaign' => $live,
                    'campaign_group' => $group, 'creatives' => array_slice($creatives['elements'], 0, self::MOST_SHOWN),
                    'truncated' => count($creatives['elements']) > self::MOST_SHOWN || $creatives['next_page_token'] !== null,
                    'next_page_token' => $creatives['next_page_token'], 'refreshed_at' => now()->toIso8601String(),
                    'note' => 'Sponsored creatives are the serving ads. Their local ad IDs and referenced post URNs are separate identifiers. A non-null next_page_token means this is not the complete list.']);
            } catch (\Throwable $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage(),
                    'campaign' => $live, 'campaign_group' => $group,
                    'note' => 'Report only returned live parent data. The remaining structure is unavailable, not empty; do not invent creative IDs or statuses.']);
            }
        }

        $platform = (string) ($campaign?->platform ?? 'meta');

        if ($platform === 'google') {
            return $this->google($campaignId, $campaign?->name, trim((string) ($arguments['ad_set_id'] ?? '')), $campaign?->ad_account_id);
        }

        // Meta, Google and LinkedIn can answer this; the rest are said by name
        // rather than returning an empty structure, which would read as "this
        // campaign has nothing in it".
        if ($platform !== 'meta') {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Listing the inside of a campaign is only available for Meta and Google campaigns. This one is on %s.', ucfirst($platform)),
                'note' => 'Say so plainly and do not guess at what is in it.',
            ]);
        }

        $account = $campaign?->ad_account_id;
        $meta = $this->meta->on($campaign?->id, $this->actor->describe());

        try {
            $adSets = $meta->adSets($campaignId, $account, fresh: true);
            $ads = $meta->ads(trim((string) ($arguments['ad_set_id'] ?? '')) ?: $campaignId, $account, fresh: true, withCopy: true);
        } catch (MetaException $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'This is a platform error, not an empty campaign. Do not say the campaign has no ad sets or ads.',
            ]);
        }

        $byAdSet = collect($ads)->groupBy(fn (array $ad): string => (string) ($ad['adset_id'] ?? ''));

        return $this->json([
            'ok' => true,
            'campaign_id' => $campaignId,
            'campaign' => $campaign?->name,
            'counts' => [
                'ad_sets' => count($adSets),
                'ads' => count($ads),
            ],
            'ad_sets' => array_map(fn (array $adSet): array => [
                'id' => $adSet['id'] ?? null,
                'name' => $adSet['name'] ?? null,
                'status' => $adSet['status'] ?? null,
                'daily_budget' => $adSet['daily_budget'] ?? null,
                'lifetime_budget' => $adSet['lifetime_budget'] ?? null,
                'optimization_goal' => $adSet['optimization_goal'] ?? null,
                'ads' => $byAdSet->get((string) ($adSet['id'] ?? ''), collect())->count(),
            ], array_slice($adSets, 0, self::MOST_SHOWN)),
            'ads' => array_map(function (array $ad): array {
                $copy = (new AdCreativeCopy)->fromAd($ad);

                return [
                    'id' => $ad['id'] ?? null,
                    'name' => $ad['name'] ?? null,
                    'status' => $ad['status'] ?? null,
                    // Both, because they disagree in the case that matters: an ad
                    // can be ACTIVE under a paused ad set and show nothing.
                    'effective_status' => $ad['effective_status'] ?? null,
                    'ad_set_id' => $ad['adset_id'] ?? null,
                    'headline' => $copy['headline'],
                    'primary_text' => $copy['primary_text'],
                    'description' => $copy['description'],
                    'url' => $copy['url'],
                ];
            }, array_slice($ads, 0, self::MOST_SHOWN)),
            // Said rather than left to be inferred from a list that stops.
            'truncated' => count($adSets) > self::MOST_SHOWN || count($ads) > self::MOST_SHOWN,
            'note' => $this->note($adSets, $ads),
        ]);
    }

    /**
     * The Google side, in Google's own vocabulary.
     *
     * The shared credentials, pointed at the account the campaign is on. The
     * credentials are the install's; the account is the campaign's, because the
     * chat now asks which child of the manager to use and reading the wrong one
     * reports a campaign's own entities as missing.
     */
    private function google(string $campaignId, ?string $name, string $adGroupId, ?string $adAccountId = null): Stringable|string
    {
        $connection = GoogleAdsConnection::shared();

        if ($connection === null) {
            return $this->json([
                'ok' => false,
                'error' => ucfirst(GoogleAdsConnection::missingReason()).'.',
                'note' => 'This is a connection problem, not an empty campaign. Do not say the campaign has nothing in it.',
            ]);
        }

        // The account the campaign is on, not the configured default. See
        // GoogleAdsConnection::onCustomer - the allow list still gates it.
        $connection = $connection->onCustomer($adAccountId);

        try {
            $structure = $this->google->readCampaignStructure($connection, $campaignId, $adGroupId ?: null);
        } catch (RuntimeException $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'This is a platform error, not an empty campaign. Do not say the campaign has no ad groups or ads.',
            ]);
        }

        $adGroups = $structure['ad_groups'];
        $ads = $structure['ads'];
        $assetGroups = $structure['asset_groups'];
        $counts = collect($ads)->countBy(fn (array $ad): string => $ad['ad_group_id']);

        return $this->json([
            'ok' => true,
            'platform' => 'google',
            'campaign_id' => $campaignId,
            'campaign' => $name,
            'campaign_type' => $structure['channel_type'],
            'counts' => [
                'ad_groups' => count($adGroups),
                'ads' => count($ads),
                'asset_groups' => count($assetGroups),
            ],
            'ad_groups' => array_map(fn (array $group): array => [
                ...$group,
                'ads' => $counts->get($group['id'], 0),
            ], array_slice($adGroups, 0, self::MOST_SHOWN)),
            'ads' => array_slice($ads, 0, self::MOST_SHOWN),
            'asset_groups' => array_slice($assetGroups, 0, self::MOST_SHOWN),
            'truncated' => count($adGroups) > self::MOST_SHOWN
                || count($ads) > self::MOST_SHOWN
                || count($assetGroups) > self::MOST_SHOWN,
            'note' => $this->googleNote($adGroups, $ads, $assetGroups),
        ]);
    }

    /**
     * @param  list<array<string,mixed>>  $adGroups
     * @param  list<array<string,mixed>>  $ads
     * @param  list<array<string,mixed>>  $assetGroups
     */
    private function googleNote(array $adGroups, array $ads, array $assetGroups): string
    {
        if ($adGroups === [] && $ads === [] && $assetGroups === []) {
            return 'The platform returned no ad groups, ads or asset groups for this campaign. Say '
                .'that, and do not offer to pause or edit anything in it.';
        }

        // Named as asset groups because that is what the buyer sees in the
        // Google Ads UI, and what any later instruction will have to say.
        if ($assetGroups !== []) {
            return sprintf(
                'This is a Performance Max campaign: say it has %d asset group(s), not ad sets or '
                    .'ad groups. Use these ids for anything they want done to a specific asset '
                    .'group - do not invent or guess an id. Note that pausing an individual asset '
                    .'group is not something this product can do yet, so do not offer it.',
                count($assetGroups),
            );
        }

        return sprintf(
            'Say the counts in one line: %d ad group(s) and %d ad(s). Call them ad groups, not ad '
                .'sets - that is Meta\'s word and this is Google. List names only if they ask. Use '
                .'these ids for anything they want done to a specific ad group or ad - do not '
                .'invent or guess an id, and do not reuse one from an earlier turn without checking '
                .'it is still here. An ad can be ENABLED and still serve nothing if its '
                .'approval_status is DISAPPROVED, so read that before saying an ad is running.',
            count($adGroups),
            count($ads),
        );
    }

    /**
     * @param  list<array<string,mixed>>  $adSets
     * @param  list<array<string,mixed>>  $ads
     */
    private function note(array $adSets, array $ads): string
    {
        if ($adSets === [] && $ads === []) {
            return 'The platform returned no ad sets and no ads for this campaign. Say that, and do '
                .'not offer to pause or edit anything in it.';
        }

        return sprintf(
            'Say the counts in one line: %d ad set(s) and %d ad(s). List names only if they ask. '
                .'Use these ids for anything they want done to a specific ad set or ad - do not '
                .'invent or guess an id, and do not reuse one from an earlier turn without checking '
                .'it is still here. Each ad includes primary_text, headline, description, and url '
                .'from its creative. Quote those when asked for the ad copy or destination. An empty '
                .'string means that line is not set. Do not say the copy or URL is unavailable.',
            count($adSets),
            count($ads),
        );
    }
}
