<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Knowledge Base Source Model
 *
 * Handles storage and retrieval for Knowledge Base sources using CPT.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/models
 */

class Kitsune_AI_Platform_KB_Source_Model extends Kitsune_AI_Platform_Base_Model {

    const POST_TYPE = 'kitsune_ai_kb_source';

    /**
     * Get post type slug.
     *
     * @return string
     */
    protected function get_post_type() {
        return self::POST_TYPE;
    }

    /**
     * Get meta prefix override
     *
     * @return string
     */
    protected function get_meta_prefix() {
        return '_ai_platform_kb_';
    }

    /**
     * Get default meta fields.
     */
    protected function get_default_meta() {
        return array(
            'type'         => 'wordpress',
            'status'       => 'pending',
            'chunks'       => 0,
            'last_updated' => current_time('mysql'),
        );
    }

    /**
     * Create a new KB source
     *
     * @param array $data
     * @return int|WP_Error
     */
    public function create($data) {
        $name = isset($data['name']) ? sanitize_text_field($data['name']) : '';
        if ($name === '') {
            $name = $this->derive_name_from_payload($data);
        }

        $config = $data;
        $post_data = array(
            'post_type'    => $this->get_post_type(),
            'post_title'   => $name,
            'post_content' => wp_json_encode($config),
            'post_status'  => 'private',
            'post_author'  => get_current_user_id(),
        );

        $post_id = wp_insert_post($post_data, true);
        if (is_wp_error($post_id)) {
            return $post_id;
        }

        $this->save_meta($post_id, $data);

        return $post_id;
    }

    /**
     * Update source status and metadata
     *
     * @param int    $id
     * @param string $status
     * @param int    $chunks
     * @return array|WP_Error
     */
    public function update_status($id, $status, $chunks = null) {
        $post = get_post($id);
        if (!$post || $post->post_type !== $this->get_post_type()) {
            return new WP_Error('not_found', __('Source not found', 'kitsune-ai-platform'));
        }

        update_post_meta($id, $this->get_meta_prefix() . 'status', sanitize_text_field($status));
        update_post_meta($id, $this->get_meta_prefix() . 'last_updated', current_time('mysql'));

        if ($chunks !== null) {
            update_post_meta($id, $this->get_meta_prefix() . 'chunks', intval($chunks));
        }

        return $this->format_post(get_post($id));
    }

    /**
     * Search sources by query
     *
     * @param string $query
     * @param int    $limit
     * @return array
     */
    public function search($query, $limit = 10) {
        $query_args = array(
            'post_type'      => $this->get_post_type(),
            'posts_per_page' => $limit,
            's'              => $query,
            'post_status'    => array('private', 'publish'),
        );

        $posts = get_posts($query_args);
        $results = array();

        foreach ($posts as $post) {
            $content = $post->post_content;
            $decoded = json_decode($content, true);
            if (is_array($decoded)) {
                $content = $decoded['paste']['content'] ?? $decoded['content'] ?? $content;
            }
            $results[] = array(
                'source' => $post->post_title,
                'content' => wp_trim_words(wp_strip_all_tags($content), 30, '...'),
                'score' => $this->score_match($content, $query),
            );
        }

        return $results;
    }

    protected function format_post($post) {
        $type = get_post_meta($post->ID, $this->get_meta_prefix() . 'type', true);
        $status = get_post_meta($post->ID, $this->get_meta_prefix() . 'status', true);
        $chunks = get_post_meta($post->ID, $this->get_meta_prefix() . 'chunks', true);
        $last_updated = get_post_meta($post->ID, $this->get_meta_prefix() . 'last_updated', true);

        $last_updated_ts = $last_updated ? strtotime($last_updated) : strtotime($post->post_modified_gmt . ' GMT');
        $last_updated_human = $last_updated_ts ? human_time_diff($last_updated_ts, current_time('timestamp', true)) . ' ago' : '';

        return array(
            'id' => $post->ID,
            'name' => $post->post_title,
            'type' => $type ?: 'wordpress',
            'status' => $status ?: 'pending',
            'last_updated' => $last_updated_human,
            'chunks' => intval($chunks) ?: 0,
        );
    }

    private function derive_name_from_payload($data) {
        if (!empty($data['paste']['name'])) {
            return sanitize_text_field($data['paste']['name']);
        }
        if (!empty($data['crawl']['url'])) {
            return sanitize_text_field($data['crawl']['url']);
        }
        if (!empty($data['postTypeSelections']) && is_array($data['postTypeSelections'])) {
            $post_types = array_map('sanitize_text_field', array_keys($data['postTypeSelections']));
            if (!empty($post_types)) {
                return 'WordPress: ' . implode(', ', $post_types);
            }
        }
        if (!empty($data['postTypes'])) {
            return 'WordPress: ' . implode(', ', array_map('sanitize_text_field', (array) $data['postTypes']));
        }
        /* translators: %s: Knowledge Source generic name */
        return __('Knowledge Source', 'kitsune-ai-platform');
    }

    private function score_match($content, $query) {
        if ($query === '') {
            return 0.5;
        }
        $content_lower = strtolower($content);
        $query_lower = strtolower($query);
        $count = substr_count($content_lower, $query_lower);
        $score = 0.5 + min(0.45, $count * 0.05);
        return round($score, 3);
    }
}
