<?php

namespace App\Services\AI;

use App\DTOs\LandingPageAnalysis;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\Log;
use Throwable;

use function Laravel\Ai\agent;

/**
 * Audience phrases for "who should see these ads", written from the landing page.
 *
 * Meta's interest search answers a single word with the nearest catalog name,
 * which is how an ad blocker was offered "Browser games". These phrases are the
 * search terms instead: "ad blocker", "online privacy", "tracker blocker".
 */
class AudienceInterestPhrases
{
    /**
     * @return list<string>
     */
    public function forPage(LandingPageAnalysis $analysis): array
    {
        try {
            $response = agent(
                instructions: 'You name the audience interests for a Meta ad, using only what the landing page offers. '
                    .'Return short phrases a media buyer would search, such as "ad blocker", "online privacy", or "tracker blocker" for an ad-blocker page. '
                    .'Stay on the product. Do not return the brand name, a call to action, or an unrelated category.',
                schema: fn (JsonSchema $schema): array => [
                    'phrases' => $schema->array()
                        ->items($schema->string())
                        ->min(3)
                        ->max(6)
                        ->required(),
                ],
            )->prompt($this->prompt($analysis), provider: TextProviderFailover::providers());

            $phrases = $this->clean((array) ($response->toArray()['phrases'] ?? []));
        } catch (Throwable $exception) {
            Log::warning('Audience interest phrases failed', [
                'url' => $analysis->url,
                'error' => $exception->getMessage(),
            ]);
            $phrases = [];
        }

        return $phrases !== [] ? $phrases : $this->fallback($analysis);
    }

    private function prompt(LandingPageAnalysis $analysis): string
    {
        return implode("\n", array_filter([
            'Landing page: '.$analysis->url,
            'Title: '.$analysis->title,
            $analysis->description !== '' ? 'Description: '.$analysis->description : null,
            $analysis->headings !== [] ? 'Headings: '.implode(' | ', $analysis->headings) : null,
            $analysis->text !== '' ? 'Page text: '.mb_substr($analysis->text, 0, 800) : null,
        ]));
    }

    /**
     * @param  list<mixed>  $phrases
     * @return list<string>
     */
    private function clean(array $phrases): array
    {
        $unique = [];

        foreach ($phrases as $phrase) {
            $phrase = trim((string) preg_replace('/\s+/u', ' ', (string) $phrase));

            if (mb_strlen($phrase) < 3 || mb_strlen($phrase) > 60) {
                continue;
            }

            $unique[mb_strtolower($phrase)] = $phrase;
        }

        return array_slice(array_values($unique), 0, 6);
    }

    /**
     * @return list<string>
     */
    private function fallback(LandingPageAnalysis $analysis): array
    {
        $phrases = [];

        foreach ($analysis->keywords as $keyword) {
            $keyword = trim($keyword);

            if (preg_match('/\s/u', $keyword) === 1) {
                $phrases[mb_strtolower($keyword)] = $keyword;
            }
        }

        return array_slice(array_values($phrases), 0, 3);
    }
}
