<?php

namespace App\Services\AI;

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

use function Laravel\Ai\agent;

class LaravelAiScriptGenerator implements ScriptGenerator
{
    public function generate(CreativeBrief $brief): array
    {
        return $this->generateOne($brief);
    }

    public function generateVariations(CreativeBrief $brief, int $count): array
    {
        return array_map(
            fn (int $i) => $this->generateOne($brief, variationSeed: $i),
            range(1, $count),
        );
    }

    private function generateOne(CreativeBrief $brief, int $variationSeed = 1): array
    {
        $prompt = sprintf(
            "Product: %s\nFeatures: %s\nBenefits: %s\nMessaging: %s\nCTA: %s\n\nWrite video ad script variation #%d. Make the hook meaningfully different from other variations.",
            $brief->productName,
            implode(', ', $brief->features),
            implode(', ', $brief->benefits),
            $brief->messaging,
            $brief->cta,
            $variationSeed,
        );

        $response = agent(
            instructions: 'You write short-form video ad scripts using the structure Hook -> Problem -> Product -> Benefits -> CTA. Keep each section to one punchy sentence.',
            schema: fn (JsonSchema $schema) => [
                'hook' => $schema->string()->required(),
                'problem' => $schema->string()->required(),
                'product' => $schema->string()->required(),
                'benefits' => $schema->string()->required(),
                'cta' => $schema->string()->required(),
            ],
        )->prompt($prompt);

        return $response->toArray();
    }
}
