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

class WPBS_API_Client {
    private static $instance = null;

    public static function instance() {
        if (null === self::$instance) self::$instance = new self();
        return self::$instance;
    }

    private function get_api_url() {
        return 'https://pagesparkwp.com';
    }
    private function get_api_key() { return get_option('wpbs_api_key', ''); }

    private function request($endpoint, $body = []) {
        $url = $this->get_api_url() . '/api/v1/' . $endpoint;
        $api_key = $this->get_api_key();

        if (empty($url) || empty($api_key)) {
            return new WP_Error('not_configured', 'API not configured. Go to PageSpark WP > Settings.');
        }

        error_log('[PageSpark] POST ' . $url);

        $response = wp_remote_post($url, [
            'timeout' => 300,
            'redirection' => 0,
            'headers' => ['Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key],
            'body' => wp_json_encode($body),
        ]);

        if (is_wp_error($response)) {
            error_log('[PageSpark] WP_Error: ' . $response->get_error_message());
            return $response;
        }

        $code = wp_remote_retrieve_response_code($response);
        // Response may have keepalive spaces before the JSON — trim them
        $raw_body = trim(wp_remote_retrieve_body($response));
        error_log('[PageSpark] Response: ' . $code . ' — ' . substr($raw_body, 0, 200));
        $body = json_decode($raw_body, true);

        if ($code !== 200 || !$body) {
            $error_msg = is_array($body) ? ($body['error'] ?? 'API error: status ' . $code) : 'API error: status ' . $code;
            return new WP_Error('api_error', $error_msg);
        }
        return $body;
    }

    public function generate(WP_REST_Request $request) {
        $prompt = sanitize_textarea_field($request->get_param('prompt'));
        $post_id = absint($request->get_param('post_id'));
        $continuation = $request->get_param('continuation');
        $tier = sanitize_text_field($request->get_param('tier') ?: 'standard');

        if (empty($prompt)) return new WP_REST_Response(['error' => 'Prompt required'], 400);

        $body = [
            'prompt' => $prompt,
            'siteContext' => $this->build_site_context($post_id),
            'tier' => $tier,
        ];
        if (!empty($continuation)) {
            $body['continuation'] = $continuation;
        }

        $result = $this->request('generate', $body);

        if (is_wp_error($result)) {
            return new WP_REST_Response(['error' => $result->get_error_message()], 500);
        }
        return new WP_REST_Response([
            'success' => true,
            'html' => $result['html'] ?? '',
            'complete' => $result['complete'] ?? true,
        ]);
    }

    public function edit(WP_REST_Request $request) {
        $instructions = sanitize_textarea_field($request->get_param('instructions'));
        $current_html = $request->get_param('current_html');
        $post_id = absint($request->get_param('post_id'));
        $continuation = $request->get_param('continuation');
        $tier = sanitize_text_field($request->get_param('tier') ?: 'standard');

        if (empty($instructions) || empty($current_html)) {
            return new WP_REST_Response(['error' => 'Instructions and HTML required'], 400);
        }

        // CSS and JS are now embedded in currentHtml as <style> and <script> blocks
        $body = [
            'currentHtml' => $current_html,
            'instructions' => $instructions,
            'siteContext' => $this->build_site_context($post_id),
            'tier' => $tier,
        ];
        if (!empty($continuation)) {
            $body['continuation'] = $continuation;
        }
        $use_qa = $request->get_param('use_qa');
        if ($use_qa) {
            $body['useQA'] = true;
        }

        $result = $this->request('edit', $body);

        if (is_wp_error($result)) {
            return new WP_REST_Response(['error' => $result->get_error_message()], 500);
        }
        return new WP_REST_Response([
            'success' => true,
            'html' => $result['html'] ?? '',
            'complete' => $result['complete'] ?? true,
        ]);
    }

    public function test_connection(WP_REST_Request $request) {
        $url = $this->get_api_url() . '/api/health';
        $response = wp_remote_get($url, ['timeout' => 15]);

        if (is_wp_error($response)) {
            return new WP_REST_Response(['connected' => false, 'error' => $response->get_error_message()]);
        }
        $body = json_decode(wp_remote_retrieve_body($response), true);
        return new WP_REST_Response(['connected' => true, 'service' => $body['service'] ?? '', 'version' => $body['version'] ?? '']);
    }

    public function build_site_context($post_id = 0) {
        $context = [
            'siteName' => get_bloginfo('name'),
            'siteDescription' => get_bloginfo('description'),
            'siteUrl' => home_url(),
        ];
        $default = get_option('wpbs_default_context', '');
        if ($default) $context['businessContext'] = $default;
        if ($post_id > 0) {
            $page_ctx = get_post_meta($post_id, '_wpbs_site_context', true);
            if ($page_ctx) $context['pageContext'] = $page_ctx;
            $context['pageTitle'] = get_the_title($post_id);
        }

        // Grab images from the media library
        $context['mediaLibrary'] = $this->get_media_library_images();

        // Published pages so Claude can build proper nav links
        $context['sitePages'] = $this->get_site_pages($post_id);

        // Include theme Customizer settings (colors, fonts, etc.)
        $theme = $this->get_theme_settings();
        if (!empty($theme)) {
            $context['themeSettings'] = $theme;
        }

        return $context;
    }

    /**
     * Get all published pages with their URLs and titles
     * so Claude can generate correct internal nav links.
     */
    private function get_site_pages($current_post_id = 0) {
        $pages = get_pages(['post_status' => 'publish', 'sort_column' => 'menu_order,post_title']);
        $result = [];

        foreach ($pages as $page) {
            $entry = [
                'title' => $page->post_title,
                'url'   => get_permalink($page->ID),
                'slug'  => $page->post_name,
            ];
            if ($page->post_parent) {
                $entry['parent'] = get_the_title($page->post_parent);
            }
            if ($page->ID === $current_post_id) {
                $entry['current'] = true;
            }
            $result[] = $entry;
        }

        return $result;
    }

    /**
     * Get images from the PageSpark media index JSON file.
     * The index is maintained by WPBS_Media_Indexer with Haiku-generated
     * alt text and descriptions — no database query needed here.
     */
    private function get_media_library_images() {
        $index_file = WP_CONTENT_DIR . '/uploads/pagespark-media-index.json';
        if (!file_exists($index_file)) return [];
        $contents = file_get_contents($index_file);
        if (!$contents) return [];
        $images = json_decode($contents, true);
        if (!is_array($images)) return [];
        // Return only the fields Claude needs — no IDs
        return array_map(function($img) {
            return [
                'url'         => $img['url'],
                'filename'    => $img['filename'],
                'alt'         => $img['alt'],
                'description' => $img['description'],
            ];
        }, $images);
    }

    /**
     * Read theme Customizer settings so Claude uses the configured
     * brand identity (colors, fonts, typography) instead of guessing.
     */
    private function get_theme_settings() {
        $settings = [];

        // Colors
        $color_keys = [
            'wpbs_primary_color'   => 'primaryColor',
            'wpbs_secondary_color' => 'secondaryColor',
            'wpbs_accent_color'    => 'accentColor',
            'wpbs_heading_color'   => 'headingColor',
            'wpbs_navbar_bg'       => 'navbarBg',
            'wpbs_footer_bg'       => 'footerBg',
        ];
        foreach ($color_keys as $mod => $key) {
            $val = get_theme_mod($mod, '');
            if ($val) $settings[$key] = $val;
        }

        // Button colors
        $btn_keys = [
            'wpbs_btn_primary_bg'    => 'btnPrimaryBg',
            'wpbs_btn_primary_text'  => 'btnPrimaryText',
            'wpbs_btn_primary_hover' => 'btnPrimaryHover',
            'wpbs_btn_secondary_bg'  => 'btnSecondaryBg',
            'wpbs_btn_secondary_text'=> 'btnSecondaryText',
        ];
        foreach ($btn_keys as $mod => $key) {
            $val = get_theme_mod($mod, '');
            if ($val) $settings[$key] = $val;
        }

        // Typography
        $heading_font = get_theme_mod('wpbs_heading_font', '');
        $body_font    = get_theme_mod('wpbs_body_font', '');
        if ($heading_font) $settings['headingFont'] = $heading_font;
        if ($body_font)    $settings['bodyFont']    = $body_font;

        // Font sizes (only non-empty overrides)
        foreach (['h1','h2','h3','h4','h5','h6','p'] as $tag) {
            $val = get_theme_mod("wpbs_font_size_{$tag}", '');
            if ($val) $settings["fontSize_{$tag}"] = $val;
        }

        // Navbar config
        $navbar_style = get_theme_mod('wpbs_navbar_style', '');
        $navbar_cta   = get_theme_mod('wpbs_navbar_cta_text', '');
        $navbar_url   = get_theme_mod('wpbs_navbar_cta_url', '');
        $navbar_phone = get_theme_mod('wpbs_navbar_phone', '');
        if ($navbar_style) $settings['navbarStyle']   = $navbar_style;
        if ($navbar_cta)   $settings['navbarCtaText']  = $navbar_cta;
        if ($navbar_url)   $settings['navbarCtaUrl']   = $navbar_url;
        if ($navbar_phone) $settings['navbarPhone']    = $navbar_phone;

        return $settings;
    }

    // --- Plugin Builder API Methods ---

    public function request_plugin_build($prompt, $options = []) {
        $body = array_merge(['prompt' => $prompt], $options);
        return $this->request('plugin-builder', $body);
    }

    public function request_blob_cleanup($blob_url) {
        return $this->request('plugin-install', ['blob_url' => $blob_url]);
    }

    public function request_plugin_edit($params) {
        return $this->request('plugin-editor', $params);
    }
}
