<?php

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

class Niwa_AI_Store_Overview {
    /** @var Niwa_AI_Content_Store_Interface|null */
    private $content_store;

    public function __construct( ?Niwa_AI_Content_Store_Interface $content_store = null ) {
        $this->content_store = $content_store;
    }

    public function build() {
        if ( ! $this->content_store ) {
            return "[STORE OVERVIEW]\nNo store data available.\n[/STORE OVERVIEW]";
        }

        $data = $this->content_store->get_store_overview();
        if ( empty( $data ) || ! is_array( $data ) ) {
            return "[STORE OVERVIEW]\nNo store data available.\n[/STORE OVERVIEW]";
        }

        $lines = array();

        if ( ! empty( $data['categories'] ) && is_array( $data['categories'] ) ) {
            $parts = array();
            foreach ( $data['categories'] as $c ) {
                $name  = isset( $c['name'] ) ? (string) $c['name'] : '';
                $count = isset( $c['count'] ) ? intval( $c['count'] ) : 0;
                if ( '' !== $name ) {
                    $parts[] = $name . ' (' . $count . ')';
                }
            }
            if ( ! empty( $parts ) ) {
                $lines[] = 'Categories: ' . implode( ', ', $parts );
            }
        }

        if ( ! empty( $data['brands'] ) && is_array( $data['brands'] ) ) {
            $parts = array();
            foreach ( $data['brands'] as $b ) {
                $name  = isset( $b['name'] ) ? (string) $b['name'] : '';
                $count = isset( $b['count'] ) ? intval( $b['count'] ) : 0;
                if ( '' !== $name ) {
                    $parts[] = $name . ' (' . $count . ')';
                }
            }
            if ( ! empty( $parts ) ) {
                $lines[] = 'Brands: ' . implode( ', ', $parts );
            }
        }

        if ( isset( $data['price_min'] ) || isset( $data['price_max'] ) ) {
            $min = isset( $data['price_min'] ) ? $data['price_min'] : null;
            $max = isset( $data['price_max'] ) ? $data['price_max'] : null;
            if ( null !== $min || null !== $max ) {
                $lines[] = 'Price range: ' . ( null !== $min ? $min : '?' ) . ' - ' . ( null !== $max ? $max : '?' ) . ' RSD';
            }
        }

        if ( isset( $data['total_products'] ) ) {
            $lines[] = 'Total products: ' . intval( $data['total_products'] );
        }

        if ( ! empty( $data['attributes'] ) && is_array( $data['attributes'] ) ) {
            $parts = array();
            if ( isset( $data['attributes']['colors'] ) ) {
                $parts[] = 'Colors (' . intval( $data['attributes']['colors'] ) . ' values)';
            }
            if ( isset( $data['attributes']['sizes'] ) ) {
                $parts[] = 'Sizes (' . intval( $data['attributes']['sizes'] ) . ' values)';
            }
            if ( isset( $data['attributes']['materials'] ) ) {
                $parts[] = 'Materials (' . intval( $data['attributes']['materials'] ) . ' values)';
            }
            if ( ! empty( $parts ) ) {
                $lines[] = 'Attributes: ' . implode( ', ', $parts );
            }
        }

        if ( empty( $lines ) ) {
            $lines[] = 'No summary data available.';
        }

        $overview = "[STORE OVERVIEW]\n" . implode( "\n", $lines ) . "\n[/STORE OVERVIEW]";

        $site_knowledge = $this->build_site_knowledge_summary();
        if ( '' !== $site_knowledge ) {
            $overview .= "\n\n" . $site_knowledge;
        }

        return $overview;
    }

    /**
     * Build a rich site knowledge blob from indexed pages and site_knowledge entries.
     *
     * This is included directly in the system prompt so the LLM always knows what
     * topics and pages exist on the site, without needing to search first.
     * Includes dedicated sections for agent profile, home page, navigation, and
     * grouped page/post summaries.
     * Works on ANY site — reads from the content index dynamically.
     */
    public function build_site_knowledge_summary() {
        if ( ! $this->content_store ) {
            return '';
        }

        $cached = get_transient( 'niwa_ai_site_knowledge_blob' );
        if ( is_string( $cached ) && '' !== $cached ) {
            return $cached;
        }

        $parts         = array();
        $total_length  = 0;
        $max_length    = 10000;

        // --- Agent Profile section ---
        $agent_profile = $this->content_store->get_agent_profile_summary( 1500 );
        if ( '' !== $agent_profile ) {
            $section = "[ABOUT THIS SITE]\n" . $agent_profile . "\n[/ABOUT THIS SITE]";
            $section_len = mb_strlen( $section );
            if ( $total_length + $section_len <= $max_length ) {
                $parts[]       = $section;
                $total_length += $section_len;
            }
        }

        // --- Home Page section ---
        // Builder pages (Elementor etc.) produce very long rendered text;
        // use a generous limit so footer sections (newsletter, membership,
        // policies) are included — these are often the most asked-about topics.
        $home_page = $this->content_store->get_home_page_summary( 3000 );
        if ( '' !== $home_page ) {
            $section = "[HOME PAGE]\n" . $home_page . "\n[/HOME PAGE]";
            $section_len = mb_strlen( $section );
            if ( $total_length + $section_len <= $max_length ) {
                $parts[]       = $section;
                $total_length += $section_len;
            }
        }

        // --- Navigation section ---
        $navigation = $this->content_store->get_navigation_summary();
        if ( '' !== $navigation ) {
            $section = "[NAVIGATION]\n" . $navigation . "\n[/NAVIGATION]";
            $section_len = mb_strlen( $section );
            if ( $total_length + $section_len <= $max_length ) {
                $parts[]       = $section;
                $total_length += $section_len;
            }
        }

        // --- Grouped page summaries ---
        $summaries = $this->content_store->get_site_content_summaries( 600 );
        if ( ! empty( $summaries ) ) {
            // Skip items already covered by dedicated sections above.
            $skip_sources = array( 'agent_profile', 'home_page', 'menus', 'frontend_snapshot' );
            $grouped      = array(
                'site_info' => array(),
                'pages'     => array(),
                'posts'     => array(),
            );

            foreach ( $summaries as $item ) {
                $title       = isset( $item['title'] ) ? (string) $item['title'] : '';
                $snippet     = isset( $item['snippet'] ) ? (string) $item['snippet'] : '';
                $type        = isset( $item['type'] ) ? (string) $item['type'] : '';
                $source_type = isset( $item['source_type'] ) ? (string) $item['source_type'] : '';
                $url         = isset( $item['url'] ) ? (string) $item['url'] : '';

                if ( '' === $title ) {
                    continue;
                }

                // Skip sources that have their own dedicated sections.
                if ( in_array( $source_type, $skip_sources, true ) ) {
                    continue;
                }

                $entry = '- ' . $title;
                if ( '' !== $url ) {
                    $entry .= ' (' . $url . ')';
                }
                if ( '' !== $snippet ) {
                    $entry .= ': ' . $snippet;
                }

                if ( 'site_knowledge' === $type ) {
                    $grouped['site_info'][] = $entry;
                } elseif ( 'page' === $type ) {
                    $grouped['pages'][] = $entry;
                } else {
                    $grouped['posts'][] = $entry;
                }
            }

            // Build site info sub-section.
            if ( ! empty( $grouped['site_info'] ) ) {
                $sub = "[SITE INFO]\n" . implode( "\n", $grouped['site_info'] ) . "\n[/SITE INFO]";
                $sub_len = mb_strlen( $sub );
                if ( $total_length + $sub_len <= $max_length ) {
                    $parts[]       = $sub;
                    $total_length += $sub_len;
                }
            }

            // Build pages sub-section.
            if ( ! empty( $grouped['pages'] ) ) {
                $sub = "[SITE PAGES]\n" . implode( "\n", $grouped['pages'] ) . "\n[/SITE PAGES]";
                $sub_len = mb_strlen( $sub );
                if ( $total_length + $sub_len <= $max_length ) {
                    $parts[]       = $sub;
                    $total_length += $sub_len;
                } else {
                    // Fit as many page entries as possible.
                    $remaining = $max_length - $total_length - 30; // overhead for tags.
                    if ( $remaining > 100 ) {
                        $fitted  = array();
                        $fit_len = 0;
                        foreach ( $grouped['pages'] as $entry ) {
                            $elen = mb_strlen( $entry ) + 1;
                            if ( $fit_len + $elen > $remaining ) {
                                break;
                            }
                            $fitted[]  = $entry;
                            $fit_len  += $elen;
                        }
                        if ( ! empty( $fitted ) ) {
                            $sub = "[SITE PAGES]\n" . implode( "\n", $fitted ) . "\n[/SITE PAGES]";
                            $parts[]       = $sub;
                            $total_length += mb_strlen( $sub );
                        }
                    }
                }
            }

            // Build posts sub-section (if space remains).
            if ( ! empty( $grouped['posts'] ) && $total_length < $max_length ) {
                $remaining = $max_length - $total_length - 26;
                if ( $remaining > 100 ) {
                    $fitted  = array();
                    $fit_len = 0;
                    foreach ( $grouped['posts'] as $entry ) {
                        $elen = mb_strlen( $entry ) + 1;
                        if ( $fit_len + $elen > $remaining ) {
                            break;
                        }
                        $fitted[]  = $entry;
                        $fit_len  += $elen;
                    }
                    if ( ! empty( $fitted ) ) {
                        $sub = "[SITE POSTS]\n" . implode( "\n", $fitted ) . "\n[/SITE POSTS]";
                        $parts[]       = $sub;
                        $total_length += mb_strlen( $sub );
                    }
                }
            }
        }

        if ( empty( $parts ) ) {
            return '';
        }

        $blob = "[SITE KNOWLEDGE]\nThe following information describes this site. Use memory_search to get full details about any topic.\n\n"
            . implode( "\n\n", $parts )
            . "\n[/SITE KNOWLEDGE]";

        set_transient( 'niwa_ai_site_knowledge_blob', $blob, 15 * MINUTE_IN_SECONDS );

        return $blob;
    }
}
