<?php

namespace App\Services;

use Liquid\Template;
use Liquid\Cache\File as FileCache;
use Illuminate\Support\Facades\File;

class LiquidRenderer
{
    protected static $baseTemplatePath;

    public static function render(string $templateName, array $data = []): string
    {
        // 初始化基础模板路径(仅在首次调用时)
        if (!self::$baseTemplatePath) {
            self::$baseTemplatePath = config('liquid.template_path');
        }


        // 查找模板文件
        $templatePath = self::findTemplate($templateName);

        if (!$templatePath) {
            throw new \Exception("Template not found: {$templateName}");
        }

        // 读取 Liquid 模板文件内容
        $templateContent = File::get($templatePath);

        // 创建并解析模板
        $template = new Template();
        $template->setCache(new FileCache(['cache_dir' => storage_path('framework/cache/data')]));
        $template->parse($templateContent);

        // 渲染模板并返回结果
        return $template->render($data);
    }

    protected static function findTemplate(string $templateName): ?string
    {
        // 如果模板名没有以 .liquid 结尾,则添加 .liquid 扩展名
        if (pathinfo($templateName, PATHINFO_EXTENSION) !== 'liquid') {
            $templateName .= '.liquid';
        }

        // 处理模板名中的 . 号,将其转换为目录分隔符(不包括扩展名)
        $templateNameWithoutExtension = pathinfo($templateName, PATHINFO_FILENAME);
        $templatePathSegments = explode('.', $templateNameWithoutExtension);
        $relativePath = implode(DIRECTORY_SEPARATOR, $templatePathSegments) . '.liquid';

        // 构建预期的模板路径
        $expectedPath = self::$baseTemplatePath . DIRECTORY_SEPARATOR . $relativePath;

        if (File::exists($expectedPath)) {
            return $expectedPath;
        }

        return null;
    }
}