<?php

namespace App\Campaigns\Manager\Readers;

use App\Campaigns\Manager\PlatformEntity;
use App\Campaigns\Manager\PlatformSnapshot;
use App\Campaigns\Manager\StructureReader;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use Carbon\CarbonImmutable;
use Carbon\CarbonTimeZone;
use RuntimeException;
use Throwable;

/**
 * A Google Ads campaign in Google's vocabulary: ad groups and ads, or asset
 * groups for Performance Max. Budget and bidding live on the campaign here,
 * not on the ad group, and are recorded where Google keeps them.
 */
class GoogleStructureReader implements StructureReader
{
    public function __construct(private readonly GoogleAdsService $google) {}

    public function read(Campaign $campaign, ?string $actor = null): PlatformSnapshot
    {
        $campaignId = (string) $campaign->external_campaign_id;

        if (! preg_match('/^[0-9]+$/D', $campaignId)) {
            throw new RuntimeException('Google campaign id must be numeric.');
        }

        $connection = GoogleAdsConnection::shared()
            ?? throw new RuntimeException(ucfirst(GoogleAdsConnection::missingReason()).'.');
        $connection = $connection->onCustomer($campaign->ad_account_id);

        $profile = $this->google->readCampaignProfile($connection, $campaignId, fresh: true);

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

        $structure = $this->google->readCampaignStructure($connection, $campaignId);
        $criteria = $this->google->readManagerCriteria($connection, $campaignId);
        $audiences = ($structure['ad_groups'] ?? []) !== [] ? $this->google->readManagerAudiences($connection, $campaignId) : [];
        $targets = fn (string $type, string $path, bool $negative = false): array => array_values(array_map(
            fn (array $row): mixed => data_get($row, $path),
            array_filter($criteria, fn (array $row): bool => ($row['type'] ?? null) === $type && (bool) ($row['negative'] ?? false) === $negative),
        ));

        $entities = [new PlatformEntity(
            type: 'campaign',
            externalId: $campaignId,
            name: $profile['name'] ?? null,
            status: $profile['status'] ?? null,
            effectiveStatus: ($profile['primary_status'] ?? '') ?: null,
            settings: [
                'channel_type' => ($profile['advertising_channel_type'] ?? '') ?: ($structure['channel_type'] ?? null),
                'start_date' => ($profile['start_date'] ?? '') ?: null,
                'time_zone' => ($profile['time_zone'] ?? '') ?: null,
                'start_time' => self::moment($profile['start_date_time'] ?? null, $profile['time_zone'] ?? null),
                'end_time' => self::moment($profile['end_date_time'] ?? null, $profile['time_zone'] ?? null),
                'primary_status_reasons' => $profile['primary_status_reasons'] ?? [],
                'daily_budget' => $profile['daily_budget'] ?? null,
                'budget_resource' => ($profile['budget_resource'] ?? '') ?: null,
                'budget_shared_by' => $profile['budget_reference_count'] ?? null,
                'bid_strategy' => self::strategy((string) ($profile['bidding_strategy_type'] ?? '')),
                'bidding_strategy_type' => ($profile['bidding_strategy_type'] ?? '') ?: null,
                'bidding_portfolio' => ($profile['bidding_portfolio'] ?? '') ?: null,
                'target_cpa' => $profile['target_cpa'] ?? null,
                'target_roas' => $profile['target_roas'] ?? null,
                'frequency_caps' => $profile['frequency_caps'] ?? [],
                'network_settings' => $profile['network_settings'] ?? null,
                'geo_target_type' => $profile['geo_target_type'] ?? null,
                'conversion_goals' => $profile['conversion_goals'] ?? null,
                'manager_conversion_goals' => $profile['manager_conversion_goals'] ?? null,
                'conversion_goals_error' => $profile['conversion_goals_error'] ?? null,
                'manager_criteria' => $criteria,
                'location_targets' => $targets('LOCATION', 'location.geoTargetConstant'),
                'excluded_locations' => $targets('LOCATION', 'location.geoTargetConstant', true),
                'language_targets' => $targets('LANGUAGE', 'language.languageConstant'),
                'delivery_schedule' => $targets('AD_SCHEDULE', 'adSchedule'),
                'device_exclusions' => array_values(array_map(
                    fn (array $row): string => $row['device']['type'],
                    array_filter($criteria, fn (array $row): bool => ($row['type'] ?? null) === 'DEVICE' && (float) ($row['bidModifier'] ?? 1) === 0.0),
                )),
            ],
        )];

        foreach ($structure['ad_groups'] ?? [] as $group) {
            $entities[] = new PlatformEntity(
                type: 'ad_group',
                externalId: (string) $group['id'],
                parentType: 'campaign',
                parentExternalId: $campaignId,
                name: ($group['name'] ?? '') ?: null,
                status: ($group['status'] ?? '') ?: null,
                settings: [
                    'type' => ($group['type'] ?? '') ?: null,
                    'cpc_bid' => $group['cpc_bid'] ?? null,
                    'keywords' => $group['keywords'] ?? null,
                    'manager_audience_criteria' => $audiences[$group['id']] ?? [],
                    'audience_criteria' => array_values(array_map(
                        fn (array $row): array => array_diff_key($row, array_flip(['resourceName', 'adGroup', 'status'])),
                        $audiences[$group['id']] ?? [],
                    )),
                ],
            );
        }

        foreach ($structure['ads'] ?? [] as $ad) {
            $entities[] = new PlatformEntity(
                type: 'ad',
                externalId: (string) $ad['id'],
                parentType: 'ad_group',
                parentExternalId: ($ad['ad_group_id'] ?? '') ?: null,
                name: ($ad['name'] ?? '') ?: null,
                status: ($ad['status'] ?? '') ?: null,
                effectiveStatus: ($ad['approval_status'] ?? '') ?: null,
                settings: [
                    'headline' => ($ad['headline'] ?? '') ?: null,
                ],
            );
        }

        foreach ($structure['asset_groups'] ?? [] as $group) {
            $entities[] = new PlatformEntity(
                type: 'asset_group',
                externalId: (string) $group['id'],
                parentType: 'campaign',
                parentExternalId: $campaignId,
                name: ($group['name'] ?? '') ?: null,
                status: ($group['status'] ?? '') ?: null,
                effectiveStatus: ($group['primary_status'] ?? '') ?: null,
            );
        }

        return new PlatformSnapshot($entities);
    }

    /**
     * A run date as an ISO moment with its offset, so it compares and shows
     * like Meta's. Google reports "2026-10-07 00:00:00" in the account's zone;
     * without the zone it is not a moment at all and is left out.
     */
    private static function moment(mixed $reported, mixed $zone): ?string
    {
        if (! is_string($reported) || preg_match('/^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$/', $reported) !== 1
            || ! is_string($zone) || $zone === '') {
            return null;
        }

        try {
            return CarbonImmutable::parse($reported, new CarbonTimeZone($zone))->format('Y-m-d\TH:i:sO');
        } catch (Throwable) {
            return null;
        }
    }

    /**
     * The strategy as the manager offers it. Display still reports a target
     * CPA or ROAS as its own legacy type, where Search reports the same thing
     * as maximise conversions (value) with a target, so both read alike.
     */
    private static function strategy(string $type): ?string
    {
        return match ($type) {
            '' => null,
            'TARGET_CPA' => 'MAXIMIZE_CONVERSIONS',
            'TARGET_ROAS' => 'MAXIMIZE_CONVERSION_VALUE',
            default => $type,
        };
    }
}
