<?php

namespace App\Services\AI;

use App\Contracts\CreativeTitleGenerator;
use App\DTOs\CreativeBrief;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Str;

use function Laravel\Ai\agent;

class LaravelAiCreativeTitleGenerator implements CreativeTitleGenerator
{
    public function generate(CreativeBrief $brief, string $type): string
    {
        $prompt = sprintf(
            "Creative type: %s ad\nProduct: %s\nBenefits: %s\nMessaging: %s\nCTA: %s",
            $type,
            $brief->productName,
            implode(', ', $brief->benefits),
            $brief->messaging,
            $brief->cta,
        );

        $response = agent(
            instructions: 'You write a short, descriptive title for an ad creative so it can be recognised in a list, e.g. '
                .'"Speed Focused Banner". Reply with a single title, no quotes, no trailing punctuation, '
                .'at most 30 characters.',
            schema: fn (JsonSchema $schema) => [
                'title' => $schema->string()->required(),
            ],
        )->prompt($prompt);

        $title = trim($response->toArray()['title'] ?? '');

        return $title !== '' ? Str::limit($title, 30, '') : Str::limit($brief->productName ?: ucfirst($type).' creative', 30, '');
    }
}
