<?php

if (!defined('ABSPATH')) {
    exit;
}

final class AISBW_Post_Creator
{
    private AISBW_Topic_Repository $topics;
    private AISBW_Logger $logger;

    public function __construct(?AISBW_Topic_Repository $topics = null, ?AISBW_Logger $logger = null)
    {
        $this->topics = $topics ?: new AISBW_Topic_Repository();
        $this->logger = $logger ?: new AISBW_Logger();
    }

    public function create_from_topic(int $topic_id): int
    {
        $topic = $this->topics->get($topic_id);

        if (!$topic) {
            throw new RuntimeException(__('Topic not found.', 'guco-ai-blog-writer'));
        }

        if (!empty($topic['wp_post_id']) && get_post((int) $topic['wp_post_id'])) {
            throw new RuntimeException(__('A WordPress post already exists for this topic.', 'guco-ai-blog-writer'));
        }

        $article = json_decode((string) ($topic['generated_content'] ?? ''), true);
        $quality = json_decode((string) ($topic['quality_result'] ?? ''), true);

        if (!is_array($article)) {
            throw new RuntimeException(__('No generated article.', 'guco-ai-blog-writer'));
        }

        $this->validate_article($article);
        $quality = is_array($quality) ? $quality : [];
        $post_status = $this->should_autopublish($topic, $article, $quality) ? 'publish' : 'draft';
        $category_id = (int) ($topic['category_id'] ?: AISBW_Settings::get('aisbw_default_category_id', 0));
        $author_id = (int) AISBW_Settings::get('aisbw_default_author_id', 0);

        if ($author_id <= 0) {
            $author_id = get_current_user_id();
        }

        $postarr = [
            'post_title' => sanitize_text_field((string) $article['title']),
            'post_name' => sanitize_title((string) $article['slug']),
            'post_excerpt' => wp_kses_post((string) $article['excerpt']),
            'post_content' => wp_kses_post((string) $article['content_html']),
            'post_status' => $post_status,
            'post_type' => 'post',
            'post_author' => $author_id,
        ];

        $post_id = wp_insert_post($postarr, true);

        if (is_wp_error($post_id)) {
            throw new RuntimeException($post_id->get_error_message());
        }

        if ($category_id > 0) {
            wp_set_post_categories((int) $post_id, [$category_id]);
        }

        $tags = $this->collect_tags($topic, $article);

        if ($tags) {
            wp_set_post_terms((int) $post_id, $tags, 'post_tag');
        }

        update_post_meta((int) $post_id, '_aisbw_generated', '1');
        update_post_meta((int) $post_id, '_aisbw_topic_id', $topic_id);
        update_post_meta((int) $post_id, '_aisbw_quality_score', absint($quality['quality_score'] ?? $topic['quality_score'] ?? 0));

        if ('publish' === $post_status) {
            update_post_meta((int) $post_id, '_aisbw_autopublished', '1');
            update_post_meta((int) $post_id, '_aisbw_published_at', current_time('mysql'));
        }

        AISBW_SEO_Adapter_Factory::make()->save((int) $post_id, $article);

        if (class_exists('AISBW_Featured_Image_Premium') && (aisbw_is_premium() || AISBW_Settings::get_bool('aisbw_featured_image_enabled'))) {
            try {
                AISBW_Featured_Image_Premium::generate_for_post((int) $post_id, (string) $article['title']);
                $this->logger->info('featured_image_created', 'Wygenerowano i połączono obrazek wyróżniający wpisu.', ['post_id' => (int) $post_id], $topic_id);
            } catch (Throwable $e) {
                $this->logger->error('featured_image_failed', 'Nie udało się wygenerować obrazka wyróżniającego: ' . $e->getMessage(), ['post_id' => (int) $post_id], $topic_id);
            }
        }

        $topic_status = 'publish' === $post_status ? 'published' : 'wp_draft_created';
        $this->topics->attach_wp_post($topic_id, (int) $post_id, $topic_status);
        $this->logger->info('publish' === $post_status ? 'wp_publish_created' : 'wp_draft_created', 'Utworzono wpis WordPress.', ['post_id' => (int) $post_id], $topic_id);

        return (int) $post_id;
    }

    private function validate_article(array $article): void
    {
        foreach (['title', 'slug', 'content_html'] as $key) {
            if (empty($article[$key]) || '' === trim((string) $article[$key])) {
                throw new RuntimeException(sprintf(__('Missing required article field: %s', 'guco-ai-blog-writer'), $key));
            }
        }

        if (preg_match('/\[(?:TU|WSTAW|PLACEHOLDER|TODO)[^\]]*\]/iu', (string) $article['content_html'])) {
            throw new RuntimeException(__('Article contains placeholders.', 'guco-ai-blog-writer'));
        }
    }

    private function should_autopublish(array $topic, array $article, array $quality): bool
    {
        if (class_exists('AISBW_Autopublish_Premium')) {
            return AISBW_Autopublish_Premium::should_autopublish($topic, $article, $quality);
        }

        return false;
    }

    private function collect_tags(array $topic, array $article): array
    {
        $tags = [];

        if (!empty($topic['tags'])) {
            $tags = array_merge($tags, array_map('trim', explode(',', (string) $topic['tags'])));
        }

        if (!empty($article['tags']) && is_array($article['tags'])) {
            $tags = array_merge($tags, $article['tags']);
        }

        $tags = array_map('sanitize_text_field', $tags);
        $tags = array_filter(array_unique($tags));

        return array_values($tags);
    }
}
