<?php

namespace App\Services\AI;

use App\Contracts\CreativeBriefResolver;
use App\DTOs\CreativeBrief;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

use function Laravel\Ai\agent;

class LaravelAiCreativeBriefResolver implements CreativeBriefResolver
{
    public function fromProductUrl(string $url): CreativeBrief
    {
        $html = Http::timeout(15)->get($url)->body();

        $text = Str::of(strip_tags((string) $html))
            ->squish()
            ->limit(8000)
            ->toString();

        return $this->resolve(
            instructions: 'You are an expert marketing analyst. Extract a structured ad creative brief from the raw text of a product/landing page.',
            prompt: "Landing page URL: {$url}\n\nPage text:\n{$text}",
        );
    }

    public function fromPrompt(string $prompt): CreativeBrief
    {
        return $this->resolve(
            instructions: 'You are an expert marketing analyst. Turn the user\'s ad request into a structured ad creative brief, inferring reasonable product details from what they describe.',
            prompt: $prompt,
        );
    }

    private function resolve(string $instructions, string $prompt): CreativeBrief
    {
        $response = agent(
            instructions: $instructions,
            schema: fn (JsonSchema $schema) => [
                'product_name' => $schema->string()->description('The product or service name.')->required(),
                'benefits' => $schema->array()->items($schema->string())->description('Key customer benefits.')->required(),
                'features' => $schema->array()->items($schema->string())->description('Key product features.')->required(),
                'images' => $schema->array()->items($schema->string())->description('Any image URLs found on the page.')->required(),
                'messaging' => $schema->string()->description('The overall brand/website messaging tone and angle.')->required(),
                'cta' => $schema->string()->description('The most relevant call to action.')->required(),
            ],
        )->prompt($prompt);

        return CreativeBrief::fromArray($response->toArray());
    }
}
