<?php

declare(strict_types=1);

final class MyronDefinitionFontHeadRenderer
{
    /**
     * @param list<string> $definitionUrls
     */
    public function render(array $definitionUrls = []): string
    {
        $candidates = $definitionUrls !== []
            ? $definitionUrls
            : [StyleDefinitionRuntime::activeGoogleFontsCss2Url()];
        $urls = [];
        foreach ($candidates as $candidate) {
            $url = $this->safeGoogleFontsCss2Url((string) $candidate);
            if ($url !== '') {
                $urls[$url] = true;
            }
        }
        if ($urls === []) {
            return '';
        }

        $lines = [
            '<link rel="preconnect" href="https://fonts.googleapis.com">',
            '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>',
        ];
        foreach (array_keys($urls) as $url) {
            $lines[] = '<link rel="stylesheet" href="' . $this->escape($url) . '">';
        }

        return implode("\n", $lines);
    }

    public function safeGoogleFontsCss2Url(string $url): string
    {
        $url = trim($url);
        if ($url === '' || filter_var($url, FILTER_VALIDATE_URL) === false) {
            return '';
        }
        $parts = parse_url($url);
        if (!is_array($parts)) {
            return '';
        }
        if (
            strtolower((string) ($parts['scheme'] ?? '')) !== 'https'
            || strtolower((string) ($parts['host'] ?? '')) !== 'fonts.googleapis.com'
            || !in_array((string) ($parts['path'] ?? ''), ['/css', '/css2'], true)
            || isset($parts['user'])
            || isset($parts['pass'])
            || isset($parts['fragment'])
        ) {
            return '';
        }

        return $url;
    }

    private function escape(string $value): string
    {
        return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}
