<?php

namespace App\Services\AI;

use App\Contracts\VoiceSynthesizer;
use App\Models\Voice;
use Laravel\Ai\Audio;

class LaravelAiVoiceSynthesizer implements VoiceSynthesizer
{
    public function synthesize(string $text, Voice $voice): string
    {
        return $this->generate($text, $voice, 'creatives/audio');
    }

    public function preview(Voice $voice, string $sampleText = 'Hi, this is a preview of my voice.'): string
    {
        return $this->generate($sampleText, $voice, 'voices/previews');
    }

    private function generate(string $text, Voice $voice, string $directory): string
    {
        // The provider's own voice catalogue is the source of truth; gender/accent/tone
        // on the Voice model are metadata for the picker UI, not guaranteed 1:1 with
        // what every provider supports (documented gap, see docs/SERP-1827-PLAN.md).
        $path = Audio::of($text)
            ->voice($voice->provider_voice_id)
            ->generate()
            ->storePublicly($directory, 'public');

        if ($path === false) {
            throw new \RuntimeException('Failed to store the generated audio.');
        }

        return $path;
    }
}
