<?php

namespace boru\boruai\Tools;
class PromptTemplate
{
    private $data = [];
    private $usedItems = [];
    private $prompt;

    private $renderedPrompt;

    public function __construct($prompt = null, $data = [])
    {
        $this->setPrompt($prompt);
        $this->setData($data);
    }

    public function data($data = null)
    {
        if ($data !== null) {
            $this->data = $data;
        }
        return $this->data;
    }
    public function usedItems($usedItems = null)
    {
        if ($usedItems !== null) {
            $this->usedItems = $usedItems;
        }
        return $this->usedItems;
    }
    public function isUsed($key=null) {
        if($key === null) {
            return $this->usedItems;
        }
        return in_array($key,$this->usedItems);
    }

    public function setPrompt($prompt)
    {
        $this->prompt = $prompt;
    }
    public function setData($data)
    {
        $this->data = $data;
    }

    public function prompt($prompt = null)
    {
        if($prompt !== null) {
            $this->prompt = $prompt;
        }
        return $this->prompt;
    }

    public function render($data = null)
    {
        if ($data === null) {
            $data = $this->data;
        }
        $template = $this->prompt;
        // load from file or URL
        if (file_exists($template)) {
            $template = file_get_contents($template);
        }
        if (filter_var($template, FILTER_VALIDATE_URL)) {
            $template = file_get_contents($template);
        }
        if(!is_array($data)) {
            return $template;
        }
        $smarty = Smarty::instance();
        foreach($data as $key => $value) {
            $smarty->assign($key, $value);
        }

        //convert any {{string}} to {$string}, 'string' cannot contain spaces
        $template = preg_replace_callback('/{{([^}]+)}}/', function ($matches) {
            return '{$' . trim($matches[1]) . '}';
        }, $template);
        
        //for added compatibility, convert any {string} to {$string}, where string must be alphanumeric or underscore or '.'
        $template = preg_replace_callback('/{([a-zA-Z0-9_.]+)}/', function ($matches) {
            return '{$' . trim($matches[1]) . '}';
        }, $template);
        
        // Render the template with the provided data
        $rendered = $smarty->fetch('string:' . $template);
        // get tags
        $this->usedItems = $smarty->getTemplateVars();
        return $rendered;
    }
}
