<?php
declare(strict_types=1);

namespace Ekesto\CacheWarmup\Multilingual\Adapters;

use Ekesto\CacheWarmup\Multilingual\LanguageAdapterInterface;

/**
 * TranslatePress language adapter for URL-model multilingual resolution.
 */
final class TranslatePressAdapter implements LanguageAdapterInterface
{
    /**
     * Detect whether TranslatePress integrations are available.
     *
     * @return bool
     */
    public function isActive(): bool
    {
        $converter = $this->getUrlConverter();
        return is_object($converter)
            && method_exists($converter, 'get_lang_from_url_string')
            && method_exists($converter, 'get_url_for_language');
    }

    /**
     * Return the stable adapter key.
     *
     * @return string
     */
    public function getKey(): string
    {
        return 'translatepress';
    }

    /**
     * Resolve the TranslatePress default language code.
     *
     * @return string|null Lowercased language code, or null when unavailable.
     */
    public function getDefaultLanguage(): ?string
    {
        $settings = get_option('trp_settings');
        if (!is_array($settings) || !isset($settings['default-language'])) {
            return null;
        }

        return $this->normalizeLanguage($settings['default-language']);
    }

    /**
     * Post language is not a first-class concept in TranslatePress object model.
     *
     * @param int $postId WordPress post ID.
     * @param string $postType Post type key.
     * @return string|null
     */
    public function getPostLanguage(int $postId, string $postType): ?string
    {
        return null;
    }

    /**
     * Resolve the TranslatePress language code for a URL.
     *
     * @param string $url Absolute URL.
     * @return string|null Lowercased language code, or null when unavailable.
     */
    public function getUrlLanguage(string $url): ?string
    {
        if ($url === '' || !$this->isActive()) {
            return null;
        }

        $converter = $this->getUrlConverter();
        if (!is_object($converter) || !method_exists($converter, 'get_lang_from_url_string')) {
            return null;
        }

        try {
            $language = $converter->get_lang_from_url_string($url);
            $normalized = $this->normalizeLanguage($language);
            if ($normalized !== null) {
                return $normalized;
            }
        } catch (\Throwable) {
            return $this->getDefaultLanguage();
        }

        return $this->getDefaultLanguage();
    }

    /**
     * Resolve a post permalink using TranslatePress URL mapping.
     *
     * @param int $postId WordPress post ID.
     * @param string $postType Post type key.
     * @param string $url Raw permalink URL.
     * @return string Localized permalink URL.
     */
    public function resolvePostPermalink(int $postId, string $postType, string $url): string
    {
        if ($url === '' || !$this->isActive()) {
            return $url;
        }

        $language = $this->getUrlLanguage($url);
        if ($language === null) {
            return $url;
        }

        $converter = $this->getUrlConverter();
        if (!is_object($converter) || !method_exists($converter, 'get_url_for_language')) {
            return $url;
        }

        try {
            $localized = $converter->get_url_for_language($language, $url, '');
            if (is_string($localized) && $localized !== '') {
                return $localized;
            }
        } catch (\Throwable) {
            return $url;
        }

        return $url;
    }

    /**
     * Resolve TranslatePress URL converter component.
     *
     * @return object|null
     */
    private function getUrlConverter(): ?object
    {
        if (!class_exists('TRP_Translate_Press') || !method_exists('TRP_Translate_Press', 'get_trp_instance')) {
            return null;
        }

        $trp = \TRP_Translate_Press::get_trp_instance();
        if (!is_object($trp) || !method_exists($trp, 'get_component')) {
            return null;
        }

        $converter = $trp->get_component('url_converter');
        return is_object($converter) ? $converter : null;
    }

    /**
     * Normalize language values from third-party APIs.
     *
     * @param mixed $language
     * @return string|null
     */
    private function normalizeLanguage($language): ?string
    {
        if (!is_string($language)) {
            return null;
        }

        $language = trim($language);
        return $language !== '' ? strtolower($language) : null;
    }
}
