<?php

namespace App\Campaigns\Manager\Readers;

use App\Campaigns\Manager\Editing\AdvancedEditFields;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\PlatformEntity;
use App\Campaigns\Manager\PlatformSnapshot;
use App\Campaigns\Manager\StructureReader;
use App\Models\Campaign;
use App\Services\Meta\AdCreativeCopy;
use App\Services\Meta\Meta;
use App\Support\CurrencyMinorUnits;
use RuntimeException;

/**
 * A Meta campaign, its ad sets and its ads, read fresh from Graph.
 *
 * Budgets and bids arrive in minor units and are stored in the account's
 * currency, so a change in Ads Manager from 25.00 to 30.00 reads as that and
 * not as 2500 to 3000.
 */
class MetaStructureReader implements StructureReader
{
    /** What GraphApi asks for per edge; a full page may mean more exist. */
    private const int PAGE = 50;

    public function __construct(private readonly Meta $meta) {}

    public function read(Campaign $campaign, ?string $actor = null): PlatformSnapshot
    {
        $campaignId = (string) $campaign->external_campaign_id;
        $account = filled($campaign->ad_account_id) ? (string) $campaign->ad_account_id : null;
        $currency = (string) ($campaign->currency ?: 'USD');
        $meta = $this->meta->on($campaign->id, $actor);

        $live = $meta->campaign($campaignId, $account, fresh: true);

        if ((string) ($live['id'] ?? '') !== $campaignId) {
            throw new RuntimeException('Meta returned a different campaign than the one requested.');
        }

        if ($account !== null && filled($live['account_id'] ?? null)
            && $this->digits((string) $live['account_id']) !== $this->digits($account)) {
            throw new RuntimeException('Meta reports this campaign on a different ad account than the one it was adopted from.');
        }

        $adSets = $meta->adSets($campaignId, $account, fresh: true, detailed: true);
        $ads = $meta->ads($campaignId, $account, fresh: true, withCopy: true);

        $entities = [new PlatformEntity(
            type: 'campaign',
            externalId: $campaignId,
            name: $live['name'] ?? null,
            status: $live['status'] ?? null,
            effectiveStatus: $live['effective_status'] ?? null,
            settings: [
                'objective' => $live['objective'] ?? null,
                'buying_type' => $live['buying_type'] ?? null,
                'special_ad_categories' => $live['special_ad_categories'] ?? [],
                'daily_budget' => $this->money($live['daily_budget'] ?? null, $currency),
                'lifetime_budget' => $this->money($live['lifetime_budget'] ?? null, $currency),
                'bid_strategy' => $live['bid_strategy'] ?? null,
                // Meta reports "no limit" as 0 or as its sentinel; both read as none.
                'spend_cap' => is_numeric($live['spend_cap'] ?? null) && (int) $live['spend_cap'] > 0
                    && (string) $live['spend_cap'] !== EditCapabilities::META_NO_SPEND_CAP
                    ? $this->money($live['spend_cap'], $currency) : null,
                'start_time' => $live['start_time'] ?? null,
                'stop_time' => $live['stop_time'] ?? null,
            ],
        )];

        foreach ($adSets as $adSet) {
            if (blank($adSet['id'] ?? null)) {
                continue;
            }

            $entities[] = new PlatformEntity(
                type: 'ad_set',
                externalId: (string) $adSet['id'],
                parentType: 'campaign',
                parentExternalId: $campaignId,
                name: $adSet['name'] ?? null,
                status: $adSet['status'] ?? null,
                effectiveStatus: $adSet['effective_status'] ?? null,
                settings: [
                    'daily_budget' => $this->money($adSet['daily_budget'] ?? null, $currency),
                    'lifetime_budget' => $this->money($adSet['lifetime_budget'] ?? null, $currency),
                    'bid_strategy' => $adSet['bid_strategy'] ?? null,
                    'bid_amount' => $this->money($adSet['bid_amount'] ?? null, $currency),
                    'billing_event' => $adSet['billing_event'] ?? null,
                    'optimization_goal' => $adSet['optimization_goal'] ?? null,
                    'start_time' => $adSet['start_time'] ?? null,
                    'end_time' => $adSet['end_time'] ?? null,
                    'targeting' => $adSet['targeting'] ?? null,
                    'promoted_object' => $adSet['promoted_object'] ?? null,
                    'destination_type' => $adSet['destination_type'] ?? null,
                    'attribution_spec' => $adSet['attribution_spec'] ?? null,
                    'is_dynamic_creative' => $adSet['is_dynamic_creative'] ?? null,
                    'pacing_type' => $adSet['pacing_type'] ?? null,
                    'bid_constraints' => $adSet['bid_constraints'] ?? null,
                    'adset_schedule' => $adSet['adset_schedule'] ?? null,
                    'frequency_control_specs' => $adSet['frequency_control_specs'] ?? null,
                    'daily_min_spend_target' => $this->money($adSet['daily_min_spend_target'] ?? null, $currency),
                    'daily_spend_cap' => $this->money($adSet['daily_spend_cap'] ?? null, $currency),
                    'lifetime_min_spend_target' => $this->money($adSet['lifetime_min_spend_target'] ?? null, $currency),
                    'lifetime_spend_cap' => $this->money($adSet['lifetime_spend_cap'] ?? null, $currency),
                    'budget_schedules' => isset($adSet['budget_schedules']['data']) && ! isset($adSet['budget_schedules']['paging']['next'])
                        ? AdvancedEditFields::normalize('budget_schedules', $adSet['budget_schedules']['data'])
                        : (($adSet['is_budget_schedule_enabled'] ?? null) === false ? [] : null),
                ],
            );
        }

        $copy = new AdCreativeCopy;

        foreach ($ads as $ad) {
            if (blank($ad['id'] ?? null)) {
                continue;
            }

            $words = $copy->fromAd($ad);

            $entities[] = new PlatformEntity(
                type: 'ad',
                externalId: (string) $ad['id'],
                parentType: 'ad_set',
                parentExternalId: filled($ad['adset_id'] ?? null) ? (string) $ad['adset_id'] : null,
                name: $ad['name'] ?? null,
                status: $ad['status'] ?? null,
                effectiveStatus: $ad['effective_status'] ?? null,
                settings: [
                    'creative_id' => data_get($ad, 'creative.id'),
                    'headline' => $words['headline'],
                    'primary_text' => $words['primary_text'],
                    'description' => $words['description'],
                    'url' => $words['url'],
                ],
            );
        }

        $incomplete = [];
        $gaps = [];

        if (count($adSets) >= self::PAGE) {
            $incomplete[] = 'ad_set';
            $gaps[] = sprintf('Meta returned a full page of %d ad sets; there may be more that were not read.', self::PAGE);
        }

        if (count($ads) >= self::PAGE) {
            $incomplete[] = 'ad';
            $gaps[] = sprintf('Meta returned a full page of %d ads; there may be more that were not read.', self::PAGE);
        }

        return new PlatformSnapshot($entities, $incomplete, $gaps);
    }

    private function money(mixed $minorUnits, string $currency): ?float
    {
        return is_numeric($minorUnits) ? CurrencyMinorUnits::toMajor((string) $minorUnits, $currency) : null;
    }

    private function digits(string $account): string
    {
        return (string) preg_replace('/\D/', '', $account);
    }
}
