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

/**
 * EtchWP integration — detection, Content Hub CPTs, native admin UI, richer prompts.
 *
 * Etch uses Media props (ID-based) and Dynamic Image elements; content is stored as
 * native blocks. See docs/ETCHWP_INTEGRATION.md.
 */
class AISB_Etch {

    public static function init() {
        add_filter('admin_body_class', [__CLASS__, 'admin_body_class']);
    }

    public static function is_active() {
        if (defined('ETCH_VERSION') || defined('ETCH_PLUGIN_FILE')) {
            return true;
        }
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        $candidates = ['etch/etch.php', 'etch-wp/etch.php', 'etch-for-wordpress/etch.php'];
        foreach ($candidates as $slug) {
            if (is_plugin_active($slug)) {
                return true;
            }
        }
        return apply_filters('aisb_etch_is_active', false);
    }

    public static function version() {
        if (!self::is_active()) {
            return '';
        }
        if (!function_exists('get_plugin_data')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        foreach (['etch/etch.php', 'etch-wp/etch.php'] as $slug) {
            $file = WP_PLUGIN_DIR . '/' . $slug;
            if (file_exists($file)) {
                $data = get_plugin_data($file, false, false);
                return $data['Version'] ?? '';
            }
        }
        return defined('ETCH_VERSION') ? ETCH_VERSION : '';
    }

    public static function use_native_admin_ui() {
        if (!self::is_active()) {
            return false;
        }
        $s = aisb_get_settings();
        return !isset($s['etch_native_ui']) || !empty($s['etch_native_ui']);
    }

    public static function admin_body_class($classes) {
        if (self::use_native_admin_ui() && self::is_admin_screen()) {
            $classes .= ' aisb-etch-ui';
        }
        return $classes;
    }

    private static function is_admin_screen() {
        if (!is_admin()) {
            return false;
        }
        $hook = function_exists('get_current_screen') ? get_current_screen() : null;
        if ($hook && strpos($hook->id ?? '', 'pewit-ai-schema-builder') !== false) {
            return true;
        }
        if ($hook && in_array($hook->base ?? '', ['post', 'post-new'], true)) {
            return true;
        }
        return false;
    }

    /** CPT likely from Etch Content Hub or Etch-managed content. */
    public static function is_etch_post_type($post_type) {
        $post_type = sanitize_key($post_type);
        if (strpos($post_type, 'etch') !== false) {
            return true;
        }
        $obj = get_post_type_object($post_type);
        if ($obj && stripos($obj->labels->name ?? '', 'etch') !== false) {
            return true;
        }
        return (bool) apply_filters('aisb_etch_post_type', false, $post_type);
    }

    /**
     * Extra plain text from Etch block JSON / meta for schema prompts.
     */
    public static function extract_prompt_context($post_id) {
        $post = get_post($post_id);
        if (!$post) {
            return '';
        }
        $chunks = [];

        $content = $post->post_content;
        if ($content && strpos($content, 'etch') !== false) {
            $chunks[] = wp_strip_all_tags($content);
            if (preg_match_all('/"text"\s*:\s*"([^"]{10,})"/', $content, $m)) {
                $chunks[] = implode("\n", array_slice($m[1], 0, 20));
            }
        }

        $meta = get_post_meta($post_id);
        foreach ($meta as $key => $values) {
            if (stripos($key, 'etch') === false) {
                continue;
            }
            foreach ((array) $values as $v) {
                if (is_string($v) && strlen($v) > 10) {
                    $chunks[] = wp_strip_all_tags($v);
                }
            }
        }

        $text = trim(implode("\n", array_unique(array_filter($chunks))));
        return substr($text, 0, 8000);
    }

    public static function status_line() {
        if (!self::is_active()) {
            return __('EtchWP not detected', 'pewit-ai-schema-builder');
        }
        $ver = self::version();
        return $ver
            ? sprintf(/* translators: %s are replaced with dynamic values */ __('EtchWP %s — native UI enabled', 'pewit-ai-schema-builder'), $ver)
            : __('EtchWP detected — native UI enabled', 'pewit-ai-schema-builder');
    }
}
