<?php

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

class Niwa_AI_Admin_Autonomy_Code_Intelligence {
    const CACHE_TRANSIENT = 'niwa_ai_admin_code_intelligence_v1';

    private $site_discovery;
    private $workspace;

    public function __construct( $site_discovery = null, $workspace = null ) {
        $this->site_discovery = $site_discovery;
        $this->workspace      = $workspace;
    }

    public function register_hooks() {
        add_action( 'activated_plugin', array( $this, 'flush_cache' ) );
        add_action( 'deactivated_plugin', array( $this, 'flush_cache' ) );
        add_action( 'switch_theme', array( $this, 'flush_cache' ) );
        add_action( 'upgrader_process_complete', array( $this, 'flush_cache' ) );
    }

    public function flush_cache() {
        delete_transient( self::CACHE_TRANSIENT );
    }

    public function get_snapshot( $force = false ) {
        if ( ! $force ) {
            $cached = get_transient( self::CACHE_TRANSIENT );
            if ( is_array( $cached ) && ! empty( $cached ) ) {
                return $cached;
            }
        }

        $site = $this->site_discovery && method_exists( $this->site_discovery, 'get_snapshot' )
            ? $this->site_discovery->get_snapshot( $force )
            : array();

        $plugins = array();
        foreach ( (array) ( isset( $site['plugins'] ) ? $site['plugins'] : array() ) as $plugin ) {
            $scan = isset( $plugin['scan'] ) && is_array( $plugin['scan'] ) ? $plugin['scan'] : array();
            $plugins[] = array(
                'slug'           => isset( $plugin['slug'] ) ? (string) $plugin['slug'] : '',
                'name'           => isset( $plugin['name'] ) ? (string) $plugin['name'] : '',
                'render_hooks'   => isset( $scan['render_hooks'] ) ? array_values( (array) $scan['render_hooks'] ) : array(),
                'shortcodes'     => isset( $scan['shortcodes'] ) ? array_values( (array) $scan['shortcodes'] ) : array(),
                'template_files' => isset( $scan['template_files'] ) ? array_values( (array) $scan['template_files'] ) : array(),
                'rest_routes'    => isset( $scan['rest_routes'] ) ? array_values( (array) $scan['rest_routes'] ) : array(),
            );
        }

        $snapshot = array(
            'generated_at'    => time(),
            'theme_touchpoints' => isset( $site['theme']['touchpoints'] ) ? (array) $site['theme']['touchpoints'] : array(),
            'plugins'         => $plugins,
        );

        set_transient( self::CACHE_TRANSIENT, $snapshot, 15 * MINUTE_IN_SECONDS );
        if ( $this->workspace && method_exists( $this->workspace, 'write_json_artifact' ) ) {
            $this->workspace->write_json_artifact( 'code-intelligence-latest.json', $snapshot, 'snapshots' );
        }

        return $snapshot;
    }

    public function find_touchpoints( $query, $limit = 10 ) {
        $query    = strtolower( trim( (string) $query ) );
        $limit    = max( 1, min( 20, intval( $limit ) ) );
        $snapshot = $this->get_snapshot();
        $matches  = array();

        $theme_touchpoints = isset( $snapshot['theme_touchpoints'] ) && is_array( $snapshot['theme_touchpoints'] ) ? $snapshot['theme_touchpoints'] : array();
        foreach ( array( 'render_hooks', 'shortcodes', 'template_files', 'rest_routes', 'post_types', 'taxonomies' ) as $key ) {
            foreach ( (array) ( isset( $theme_touchpoints[ $key ] ) ? $theme_touchpoints[ $key ] : array() ) as $value ) {
                $value = (string) $value;
                if ( '' === $query || false === strpos( strtolower( $value ), $query ) ) {
                    continue;
                }
                $matches[] = array(
                    'plugin' => 'Active theme',
                    'slug'   => 'theme',
                    'match'  => $value,
                );
                if ( count( $matches ) >= $limit ) {
                    return $matches;
                }
            }
        }

        foreach ( (array) ( isset( $snapshot['plugins'] ) ? $snapshot['plugins'] : array() ) as $plugin ) {
            $haystack = array_merge(
                isset( $plugin['render_hooks'] ) ? (array) $plugin['render_hooks'] : array(),
                isset( $plugin['shortcodes'] ) ? (array) $plugin['shortcodes'] : array(),
                isset( $plugin['template_files'] ) ? (array) $plugin['template_files'] : array(),
                isset( $plugin['rest_routes'] ) ? (array) $plugin['rest_routes'] : array()
            );

            foreach ( $haystack as $value ) {
                $value = (string) $value;
                if ( '' === $query || false === strpos( strtolower( $value ), $query ) ) {
                    continue;
                }
                $matches[] = array(
                    'plugin' => isset( $plugin['name'] ) ? (string) $plugin['name'] : '',
                    'slug'   => isset( $plugin['slug'] ) ? (string) $plugin['slug'] : '',
                    'match'  => $value,
                );
                if ( count( $matches ) >= $limit ) {
                    return $matches;
                }
            }
        }

        return $matches;
    }
}
