<?php

namespace App\Campaigns\Targeting;

use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use RuntimeException;

class GoogleKeywordIdeas
{
    public function __construct(
        private readonly TargetingSelections $locations,
        private readonly CountryCatalog $countries,
        private readonly SearchKeywordSelections $keywords,
        private readonly GoogleAdsService $google,
    ) {}

    /** @return array{account_id: string, geo_targets: list<string>, language: string, ideas: list<array<string,mixed>>} */
    public function forCampaign(Campaign $campaign): array
    {
        if ($campaign->platform !== 'google' || ($campaign->campaign_type ?: 'search') !== 'search'
            || $campaign->isPublished()) {
            throw new RuntimeException('Keyword research is available for draft Google Search campaigns only.');
        }

        $connection = GoogleAdsConnection::shared()
            ?? throw new RuntimeException(GoogleAdsConnection::missingReason());
        $accountId = preg_replace('/\D/', '', (string) $campaign->ad_account_id);

        if ($accountId === '') {
            throw new RuntimeException('This campaign has no Google Ads account recorded. Choose one first.');
        }

        // The account the buyer chose, not the configured default. This read
        // compared the two and refused anything else, which is the same defect
        // the publisher and the entity tools had: once the chat asks which
        // child of the manager to use, refusing the answer contradicts the
        // question. The allow list still gates it inside CallLogger.
        $connection = $connection->onCustomer($accountId);

        $geography = $this->locations->googleGeoTargets($campaign);

        if (($geography['excluded_geo_targets'] ?? []) !== [] || ($geography['proximity_targets'] ?? []) !== []) {
            throw new RuntimeException('Keyword ideas cannot represent this campaign’s exclusions or radius exactly. Review the saved keywords directly.');
        }

        $targets = array_values(array_unique([
            ...$this->countries->resolve('google', $geography['countries'], $accountId),
            ...$geography['geo_targets'],
        ]));

        if ($targets === [] || count($targets) > 10) {
            throw new RuntimeException('Keyword ideas need 1–10 exact Google locations. Narrow the campaign geography first.');
        }

        $seeds = array_values(array_unique(array_map(
            static fn (array $keyword): string => $keyword['text'],
            array_values(array_filter($this->keywords->criteria($campaign),
                static fn (array $keyword): bool => ! $keyword['negative'])),
        )));

        if ($seeds === []) {
            throw new RuntimeException('Add landing-page or selected Search keywords before requesting keyword ideas.');
        }

        $language = 'languageConstants/'.(int) config('google-ads.language_id', 1000);

        $ideas = $this->google->keywordIdeas($connection, $targets, array_slice($seeds, 0, 10), $language);

        // Google answers a seed with the advertiser's own name near the top,
        // because that is what the page is about. Those are dropped here for
        // the same reason the landing-page suggestions drop them: a Search
        // campaign is buying intent the advertiser does not already have.
        $brand = app(BrandTerms::class);
        $brandTokens = $brand->forPage($campaign->brief?->pageAnalysis());
        $generic = array_values(array_filter(
            $ideas,
            static fn (array $idea): bool => ! $brand->isBrand((string) ($idea['term'] ?? ''), $brandTokens),
        ));

        return [
            'account_id' => $accountId,
            'geo_targets' => $targets,
            'language' => $language,
            // Never empty where Google returned something: a page whose every
            // idea carries the brand would otherwise look like no ideas at all.
            'ideas' => $generic === [] ? $ideas : $generic,
            'brand_terms_excluded' => count($ideas) - count($generic),
        ];
    }
}
