<?php

namespace App\Services\AI;

use App\Contracts\AdCopyGenerator;
use App\DTOs\CreativeBrief;
use Illuminate\Contracts\JsonSchema\JsonSchema;

use function Laravel\Ai\agent;

class LaravelAiAdCopyGenerator implements AdCopyGenerator
{
    private const ANGLES = [
        'problem_focused',
        'benefit_focused',
        'feature_focused',
        'curiosity_based',
        'offer_focused',
    ];

    public function generate(CreativeBrief $brief, int $count): array
    {
        $angles = array_map(
            fn (int $i) => self::ANGLES[$i % count(self::ANGLES)],
            range(0, $count - 1),
        );

        $prompt = sprintf(
            "Product: %s\nFeatures: %s\nBenefits: %s\nMessaging: %s\nCTA: %s\n\nWrite %d ad copy variations, one for each of these angles in order: %s.",
            $brief->productName,
            implode(', ', $brief->features),
            implode(', ', $brief->benefits),
            $brief->messaging,
            $brief->cta,
            $count,
            implode(', ', $angles),
        );

        $response = agent(
            instructions: 'You are a senior direct-response copywriter. Write concise, punchy Meta/Google ad copy.',
            schema: fn (JsonSchema $schema) => [
                'copies' => $schema->array()->items(
                    $schema->object([
                        'primary_text' => $schema->string()->required(),
                        'headline' => $schema->string()->required(),
                        'description' => $schema->string()->required(),
                        'cta' => $schema->string()->required(),
                        'angle' => $schema->string()->enum(self::ANGLES)->required(),
                    ])
                )->required(),
            ],
        )->prompt($prompt);

        return $response->toArray()['copies'];
    }
}
