<?php

/**
 * Plugin Name: AI Composer
 * Description: AI-powered composer for posts.
 * Version:     0.3.3
 * Author:      Alvin Yang
 * Author URI:  https://enigtech.com
 * License:     GPL-2.0+
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

namespace lucidpen;

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

class ComposerManager
{
    private const SLUG_MD5_OPTION_NAME = LCPN_ABBR . '_composer_manager_slug_md5';

    private OpenAiChatSession $session;

    /**
     * Each entry: [
     *   'assistant' => (object),
     *   'editor'    => (GenericEditFEP),
     *   'lister'    => (GenericListFEP)
     * ]
     * @var array
     */
    private array $composers = [];

    public function __construct(OpenAiChatSession $session)
    {
        $this->session = $session;
    }

    public function setupFrontEndPages(): void
    {
        foreach ($this->session->getAssistantFactory()->getActiveAssistantClasses() as $assistantClass) {
            $assistant = new $assistantClass();
            $editor = new GenericEditFEP($assistant);
            $lister = new GenericListFEP($assistant);

            $this->composers[] = (object) [
                'assistant' => $assistant,
                'editor' => $editor,
                'lister' => $lister,
            ];
        }
    }

    /**
     * Only calls register_slug for each editor and lister if slugs/var_names change.
     * Also flushes rewrite rules if a change is detected.
     */

    public function ensureSlugRegistered(bool $force = false): void
    {
        // Build a combined hash of all current slugs
        $slugSummary = '';
        foreach ($this->composers as $composer) {
            $assistant = $composer->assistant;
            $slugOptionName = $assistant::get_slug_option_name();
            $defaultSlug = $assistant::get_default_slug();
            $slugValue = get_option($slugOptionName, $defaultSlug);
            $slugSummary .= $slugValue . "\n";
        }

        $currentHash = md5($slugSummary);
        $optionName = self::SLUG_MD5_OPTION_NAME;

        // Ensure the option exists and is not autoloaded
        $previousHash = get_option($optionName);
        if ($previousHash === false) {
            add_option($optionName, '', '', 'no');
            $previousHash = '';
        }

        // Determine if registration is needed
        $shouldRegister = $force || ($currentHash !== $previousHash);

        if ($shouldRegister) {
            foreach ($this->composers as $composer) {
                $composer->editor->register_slug();
                $composer->lister->register_slug();
            }

            flush_rewrite_rules();

            if ($currentHash !== $previousHash) {
                update_option($optionName, $currentHash);
            }
        }
    }




    /**
     * @return array
     */
    public function getComposers(): array
    {
        return $this->composers;
    }
}

