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

/**
 * Compatibility facade for older callers.
 * Full website generation is owned by VMO_Canonical_Website_Pipeline.
 */
class VMO_Website_Generator {

    public function generate_complete_website($user_id, $consultation_data, $research_data = null) {
        if (!class_exists('VMO_Canonical_Website_Pipeline')) {
            return new WP_Error('vmo_canonical_pipeline_missing', 'Canonical website pipeline is required for website generation.');
        }

        $user_id = absint($user_id);

        // ── Zero-leak guard (May 2026): meter the website generation charge
        // up front. Catalog key 'generate_website' = $0.70 provider × 12 = $8.40
        // user charge (~12,594 VMO Credits). The actual provider calls inside
        // the pipeline are atomic AI ops billed separately; this guard ensures
        // the consolidated build-fee is never skipped.
        if ($user_id > 0
            && function_exists('vmo_is_internal_unmetered_user')
            && !vmo_is_internal_unmetered_user($user_id)
            && function_exists('vmo_deduct_tokens_for_operation')) {

            $charged = vmo_deduct_tokens_for_operation($user_id, 'generate_website');
            if ($charged === false) {
                return new WP_Error('vmo_insufficient_credits',
                    'Not enough VMO Credits to generate a complete website. Please top up or upgrade your plan.',
                    ['status' => 402, 'operation' => 'generate_website']
                );
            }
        }

        $payload = is_array($consultation_data)
            ? $consultation_data
            : array('consultation_data' => $consultation_data);

        if (is_array($research_data)) {
            $payload['research_data'] = $research_data;
        }

        $payload['legacy_generator_user_id'] = $user_id;
        $session_id = $this->resolve_session_id($payload);

        return VMO_Canonical_Website_Pipeline::get_instance()->run_from_consultation_payload($session_id, $payload);
    }

    private function resolve_session_id(array $payload) {
        foreach (array('session_id', 'consultation_session_id', 'id') as $session_key) {
            if (!empty($payload[$session_key]) && is_scalar($payload[$session_key])) {
                return sanitize_text_field((string) $payload[$session_key]);
            }
        }

        return 'vmo_legacy_generator_' . wp_generate_uuid4();
    }
}