<?php

namespace App\Imports\Blog;

use App\Imports\Blog\Contracts\BlogFileParser;
use Illuminate\Support\Str;

class WordPressXmlParser implements BlogFileParser
{
    public function __construct(
        private readonly string $templateSlug = 'blog-article',
        private readonly ?string $defaultPageCategory = null,
    ) {
        //
    }

    /** @return BlogArticleData[] */
    public function parse(string $fileContents): array
    {
        $xml = simplexml_load_string($fileContents, 'SimpleXMLElement', LIBXML_NOCDATA);

        if ($xml === false) {
            return [];
        }

        $wpNamespace = 'http://wordpress.org/export/1.2/';
        $contentNamespace = 'http://purl.org/rss/1.0/modules/content/';
        $excerptNamespace = 'http://wordpress.org/export/1.2/excerpt/';

        $attachments = [];
        foreach ($xml->channel->item as $item) {
            $wp = $item->children($wpNamespace);
            if ((string) $wp->post_type === 'attachment') {
                $attachments[(string) $wp->post_id] = (string) $wp->attachment_url;
            }
        }

        $articles = [];
        foreach ($xml->channel->item as $item) {
            $wp = $item->children($wpNamespace);

            if ((string) $wp->post_type !== 'post' || (string) $wp->status !== 'publish') {
                continue;
            }

            $content = $item->children($contentNamespace);
            $excerpt = $item->children($excerptNamespace);

            $featuredImageUrl = null;
            $seoTitle = null;
            $seoDescription = null;

            foreach ($wp->postmeta as $meta) {
                $metaKey = (string) $meta->meta_key;
                if ($metaKey === '_thumbnail_id') {
                    $thumbnailId = (string) $meta->meta_value;
                    if (isset($attachments[$thumbnailId])) {
                        $featuredImageUrl = $attachments[$thumbnailId];
                    }
                } elseif ($metaKey === '_yoast_wpseo_title') {
                    $value = (string) $meta->meta_value;
                    $seoTitle = str_contains($value, '%%') ? null : $value;
                } elseif ($metaKey === '_yoast_wpseo_metadesc') {
                    $seoDescription = (string) $meta->meta_value;
                }
            }

            $postContent = (string) $content->encoded;
            if (!$featuredImageUrl) {
                if (preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $postContent, $matches)) {
                    $featuredImageUrl = $matches[1];
                }
            }

            $categories = [];
            foreach ($item->category as $cat) {
                $attrs = $cat->attributes();
                if ((string) ($attrs['domain'] ?? '') === 'category') {
                    $categories[] = [
                        'slug' => (string) $attrs['nicename'] ?? '',
                        'name' => (string) $cat ?? '',
                    ];
                }
            }

            $slug = null;
            $link = (string) $item->link;
            if ($link) {
                $urlPath = rtrim(parse_url($link, PHP_URL_PATH) ?? '', '/');
                $slug = basename($urlPath) ?: null;
            }
            if (empty($slug)) {
                $slug = Str::slug((string) $item->title);
            }

            $articles[] = new BlogArticleData(
                title: (string) $item->title,
                slug: $slug,
                body: $postContent,
                excerpt: (string) $excerpt->encoded,
                featuredImageUrl: $featuredImageUrl,
                publishedAt: (string) $wp->post_date,
                pageCategory: $this->defaultPageCategory ?? 'blog',
                templateSlug: $this->templateSlug,
                categories: $categories,
                seoTitle: $seoTitle,
                seoDescription: $seoDescription,
            );
        }

        return $articles;
    }
}
