<?php

namespace Lokalize\Translators;

class Autopilot {

    protected array $config = [];
    protected $app;

    public function __construct(array $config = []) {
        $this->config = $config;
        $this->app = $config['app'];
    }

    public function translate(string $text, string $to, $context = null) {

        if (!$this->app->module('autopilot')) {
             return ['error' => 'Autopilot addon not available'];
        }

        try {
            $client = $this->app->module('autopilot')->client();
            $model = $this->app->module('autopilot')->chatModel();

            $prompt = $text;

            if ($context) {
                $prompt = "Context: {$context}\n\nText: {$text}";
            }

            $response = $client->chat()->create([
                'model' => $model,
                'messages' => [
                    ['role' => 'system', 'content' => "You are a professional translator. Translate the input text to the target language locale: {$to}. The input may contain HTML, if so, preserve the HTML structure and only translate the content. If context is provided, use it to resolve ambiguities. Output ONLY the translated text."],
                    ['role' => 'user', 'content' => $prompt],
                ],
            ]);

            return trim($response->choices[0]->message->content);

        } catch (\Throwable $e) {
            return ['error' => $e->getMessage()];
        }
    }
}
