<?php

if (!function_exists('custausu_support_report_logs_dir')) {
  function custausu_support_report_logs_dir(): string {
    $uploads = function_exists('wp_upload_dir') ? wp_upload_dir(null, false) : [];

    if (!empty($uploads['basedir']) && is_string($uploads['basedir'])) {
      return rtrim($uploads['basedir'], '/') . '/custom-auth-suite/logs';
    }

    return rtrim(get_temp_dir(), '/') . '/custom-auth-suite/logs';
  }
}

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


/*
 * CAS support report diagnostics owner.
 *
 * This module builds an explicit support snapshot for troubleshooting. Direct
 * read-only $wpdb calls are intentional for database version and CAS custom-table
 * presence checks because WordPress has no higher-level API for these diagnostic
 * facts.
 *
 * These queries do not modify state and should reflect the current environment at
 * report-generation time, so caching is intentionally avoided. Do not copy these
 * disables to request/input/rendering code.
 */
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery -- Intentional read-only support diagnostics.
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching -- Support reports must reflect current environment state.


/**
 * CAS Support Report
 *
 * Generates a redacted, privacy-safe JSON report for support workflows.
 */

if (!function_exists('custausu_support_report_is_sensitive_key')) {
  function custausu_support_report_is_sensitive_key(string $key): bool {
    $key = strtolower($key);

    foreach ([
      'password',
      'passwd',
      'secret',
      'token',
      'license_key',
      'api_key',
      'private_key',
      'signature',
      'authorization',
      'cookie',
      'nonce',
      'salt',
      'client_secret',
      'access_key',
      'refresh',
    ] as $needle) {
      if (strpos($key, $needle) !== false) return true;
    }

    return false;
  }
}

if (!function_exists('custausu_support_report_redact_scalar')) {
  function custausu_support_report_redact_scalar($value) {
    if ($value === null || is_bool($value) || is_int($value) || is_float($value)) return $value;

    $value = (string)$value;
    if ($value === '') return '';

    return '[redacted]';
  }
}

if (!function_exists('custausu_support_report_redact')) {
  function custausu_support_report_redact($value, string $key = '') {
    if (custausu_support_report_is_sensitive_key($key)) {
      return custausu_support_report_redact_scalar($value);
    }

    if (is_array($value)) {
      $out = [];
      foreach ($value as $k => $v) {
        $child_key = is_string($k) ? $k : (string)$k;
        $out[$k] = custausu_support_report_redact($v, $child_key);
      }
      return $out;
    }

    if (is_object($value)) {
      return custausu_support_report_redact((array)$value, $key);
    }

    if (is_string($value)) {
      $trimmed = trim($value);

      if (preg_match('/CAS-[A-Z0-9-]{8,}/i', $trimmed)) {
        return '[redacted-license-like-string]';
      }

      if (stripos($trimmed, '-----BEGIN') !== false && stripos($trimmed, 'KEY-----') !== false) {
        return '[redacted-key-material]';
      }
    }

    return $value;
  }
}

if (!function_exists('custausu_support_report_plugin_inventory_empty_groups')) {
  function custausu_support_report_plugin_inventory_empty_groups(): array {
    return [
      'active' => [],
      'inactive' => [],
      'network_active' => [],
      'must_use' => [],
      'drop_ins' => [],
    ];
  }
}

if (!function_exists('custausu_support_report_plugin_slug_from_file')) {
  function custausu_support_report_plugin_slug_from_file(string $plugin_file): string {
    $plugin_file = ltrim(wp_normalize_path(trim($plugin_file)), '/');

    if ($plugin_file === '') {
      return 'unknown-plugin';
    }

    $parts = array_values(array_filter(explode('/', $plugin_file), 'strlen'));
    $candidate = count($parts) > 1
      ? (string)$parts[0]
      : (string)pathinfo((string)end($parts), PATHINFO_FILENAME);

    $slug = sanitize_title($candidate);

    return $slug !== '' ? $slug : 'unknown-plugin';
  }
}

if (!function_exists('custausu_support_report_plugin_safe_text')) {
  function custausu_support_report_plugin_safe_text($value, int $max_length = 190): string {
    $value = sanitize_text_field((string)$value);

    if ($max_length > 0 && strlen($value) > $max_length) {
      $value = substr($value, 0, $max_length);
    }

    return $value;
  }
}

if (!function_exists('custausu_support_report_plugin_inventory_is_relevant')) {
  function custausu_support_report_plugin_inventory_is_relevant(
    string $plugin_file,
    array $plugin_data
  ): bool {
    $own_patterns = [
      'custom-auth-suite',
      'cas-license-server',
      'cas-support-desk',
      'custausu-remote-messages',
      'cas-site-edition',
      'cas-local-safety-guard',
    ];

    if (function_exists('custausu_compatibility_plugin_matches_patterns')) {
      if (custausu_compatibility_plugin_matches_patterns(
        $plugin_file,
        $plugin_data,
        $own_patterns
      )) {
        return true;
      }

      if (function_exists('custausu_compatibility_plugin_catalog')) {
        foreach (custausu_compatibility_plugin_catalog() as $rule) {
          if (
            is_array($rule)
            && custausu_compatibility_plugin_matches_patterns(
              $plugin_file,
              $plugin_data,
              (array)($rule['patterns'] ?? [])
            )
          ) {
            return true;
          }
        }
      }

      return false;
    }

    $haystack = strtolower(
      $plugin_file . ' '
      . (string)($plugin_data['Name'] ?? '') . ' '
      . (string)($plugin_data['TextDomain'] ?? '')
    );

    foreach ($own_patterns as $pattern) {
      if (strpos($haystack, $pattern) !== false) {
        return true;
      }
    }

    return false;
  }
}

if (!function_exists('custausu_support_report_plugin_inventory_item')) {
  function custausu_support_report_plugin_inventory_item(
    string $plugin_file,
    array $plugin_data,
    string $status
  ): array {
    $allowed_statuses = [
      'active',
      'inactive',
      'network-active',
      'must-use',
      'drop-in',
    ];

    if (!in_array($status, $allowed_statuses, true)) {
      $status = 'inactive';
    }

    $slug = custausu_support_report_plugin_slug_from_file($plugin_file);
    $name = custausu_support_report_plugin_safe_text(
      $plugin_data['Name'] ?? ''
    );

    if ($name === '') {
      $name = $slug;
    }

    return [
      'name' => $name,
      'slug' => $slug,
      'version' => custausu_support_report_plugin_safe_text(
        $plugin_data['Version'] ?? '',
        64
      ),
      'status' => $status,
    ];
  }
}

if (!function_exists('custausu_support_report_plugin_inventory_normalize')) {
  function custausu_support_report_plugin_inventory_normalize(
    array $standard_plugins,
    array $active_plugins,
    array $network_active_plugins,
    array $mu_plugins,
    array $drop_ins
  ): array {
    $inventory = [
      'schema_version' => 1,
      'known_cas_relevant' => custausu_support_report_plugin_inventory_empty_groups(),
      'other' => custausu_support_report_plugin_inventory_empty_groups(),
      'counts' => [
        'known_cas_relevant' => [],
        'other' => [],
      ],
    ];

    $active_lookup = [];
    foreach ($active_plugins as $plugin_file) {
      $plugin_file = wp_normalize_path((string)$plugin_file);

      if ($plugin_file !== '') {
        $active_lookup[$plugin_file] = true;
      }
    }

    $network_lookup = [];
    foreach ($network_active_plugins as $plugin_file) {
      $plugin_file = wp_normalize_path((string)$plugin_file);

      if ($plugin_file !== '') {
        $network_lookup[$plugin_file] = true;
      }
    }

    $append = static function(
      array &$target,
      string $plugin_file,
      array $plugin_data,
      string $status
    ): void {
      $bucket = custausu_support_report_plugin_inventory_is_relevant(
        $plugin_file,
        $plugin_data
      )
        ? 'known_cas_relevant'
        : 'other';

      $group = 'active';

      if ($status === 'inactive') {
        $group = 'inactive';
      } elseif ($status === 'network-active') {
        $group = 'network_active';
      } elseif ($status === 'must-use') {
        $group = 'must_use';
      } elseif ($status === 'drop-in') {
        $group = 'drop_ins';
      }

      $target[$bucket][$group][] = custausu_support_report_plugin_inventory_item(
        $plugin_file,
        $plugin_data,
        $status
      );
    };

    foreach ($standard_plugins as $plugin_file => $plugin_data) {
      $plugin_file = wp_normalize_path((string)$plugin_file);
      $plugin_data = is_array($plugin_data) ? $plugin_data : [];

      if (isset($network_lookup[$plugin_file])) {
        $status = 'network-active';
      } elseif (isset($active_lookup[$plugin_file])) {
        $status = 'active';
      } else {
        $status = 'inactive';
      }

      $append($inventory, $plugin_file, $plugin_data, $status);
    }

    foreach ($mu_plugins as $plugin_file => $plugin_data) {
      $append(
        $inventory,
        wp_normalize_path((string)$plugin_file),
        is_array($plugin_data) ? $plugin_data : [],
        'must-use'
      );
    }

    foreach ($drop_ins as $plugin_file => $plugin_data) {
      $append(
        $inventory,
        wp_normalize_path((string)$plugin_file),
        is_array($plugin_data) ? $plugin_data : [],
        'drop-in'
      );
    }

    foreach (['known_cas_relevant', 'other'] as $bucket) {
      foreach (array_keys(custausu_support_report_plugin_inventory_empty_groups()) as $group) {
        usort(
          $inventory[$bucket][$group],
          static function(array $left, array $right): int {
            $name_compare = strcasecmp(
              (string)($left['name'] ?? ''),
              (string)($right['name'] ?? '')
            );

            if ($name_compare !== 0) {
              return $name_compare;
            }

            return strcasecmp(
              (string)($left['slug'] ?? ''),
              (string)($right['slug'] ?? '')
            );
          }
        );

        $inventory['counts'][$bucket][$group] = count(
          $inventory[$bucket][$group]
        );
      }
    }

    return $inventory;
  }
}

if (!function_exists('custausu_support_report_plugin_inventory')) {
  function custausu_support_report_plugin_inventory(): array {
    if (function_exists('custausu_compatibility_load_plugin_functions')) {
      custausu_compatibility_load_plugin_functions();
    } elseif (!function_exists('get_plugins')) {
      require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $standard_plugins = function_exists('get_plugins')
      ? (array)get_plugins()
      : [];

    $mu_plugins = function_exists('get_mu_plugins')
      ? (array)get_mu_plugins()
      : [];

    $drop_ins = function_exists('get_dropins')
      ? (array)get_dropins()
      : [];

    $active_plugins = array_values((array)get_option('active_plugins', []));
    $network_active_plugins = is_multisite()
      ? array_keys((array)get_site_option('active_sitewide_plugins', []))
      : [];

    return custausu_support_report_plugin_inventory_normalize(
      $standard_plugins,
      $active_plugins,
      $network_active_plugins,
      $mu_plugins,
      $drop_ins
    );
  }
}

if (!function_exists('custausu_support_report_mu_plugin_inventory')) {
  function custausu_support_report_mu_plugin_inventory(): array {
    $inventory = custausu_support_report_plugin_inventory();

    return array_values(array_merge(
      (array)($inventory['known_cas_relevant']['must_use'] ?? []),
      (array)($inventory['other']['must_use'] ?? [])
    ));
  }
}

if (!function_exists('custausu_support_report_theme_info')) {
  function custausu_support_report_theme_info(): array {
    $theme = wp_get_theme();

    return [
      'name' => $theme ? (string)$theme->get('Name') : '',
      'version' => $theme ? (string)$theme->get('Version') : '',
      'stylesheet' => $theme ? (string)$theme->get_stylesheet() : '',
      'template' => $theme ? (string)$theme->get_template() : '',
    ];
  }
}

if (!function_exists('custausu_support_report_db_info')) {
  function custausu_support_report_db_info(): array {
    global $wpdb;

    $db_version = '';
    try {
      $db_version = (string)$wpdb->get_var('SELECT VERSION()');
    } catch (Throwable $e) {
      $db_version = '';
    }

    return [
      'db_version' => $db_version,
      'prefix_length' => strlen((string)$wpdb->prefix),
      'charset' => (string)$wpdb->charset,
      'collate' => (string)$wpdb->collate,
    ];
  }
}

if (!function_exists('custausu_support_report_build_info')) {
  function custausu_support_report_build_info(): array {
    return [
      'cas_version' => defined('CUSTAUSU_VERSION') ? (string)CUSTAUSU_VERSION : '',
      'build_edition' => 'freemium_wporg',
      'build_package_plan' => 'freemium',
      'package_debug' => function_exists('custausu_build_package_debug_info')
        ? custausu_build_package_debug_info()
        : [],
      'support_url_configured' => defined('CUSTAUSU_BUILD_SUPPORT_URL')
        && trim((string)CUSTAUSU_BUILD_SUPPORT_URL) !== '',
      'upgrade_url_configured' => defined('CUSTAUSU_BUILD_UPGRADE_URL')
        && trim((string)CUSTAUSU_BUILD_UPGRADE_URL) !== '',
      'external_support_public_key_present' => defined('CUSTAUSU_SUPPORT_DIAGNOSTICS_PUBLIC_KEY')
        && trim((string)CUSTAUSU_SUPPORT_DIAGNOSTICS_PUBLIC_KEY) !== '',
    ];
  }
}

if (!function_exists('custausu_support_report_expected_template_for_route')) {
  function custausu_support_report_expected_template_for_route(string $route_key): string {
    return match ($route_key) {
      'login' => 'account-login.php',
      'register' => 'account-register.php',
      'lostpassword' => 'lost-password.php',
      'lostpassword_confirm' => 'lost-password-confirm.php',
      default => '',
    };
  }
}

if (!function_exists('custausu_support_report_routes_snapshot')) {
  function custausu_support_report_routes_snapshot(): array {
    $opt = get_option('custausu_global_settings', []);
    $opt = is_array($opt) ? $opt : [];

    $lang = sanitize_key((string)($opt['routes_default_lang'] ?? ''));
    if ($lang === '') {
      $site_locale = (string)get_option('WPLANG');
      if ($site_locale === '') $site_locale = 'en_US';
      $lang = sanitize_key(strtolower(explode('_', $site_locale)[0] ?? 'en'));
    }
    $langs = [$lang ?: 'en'];

    $routes_ids = is_array($opt['routes_page_ids'] ?? null) ? $opt['routes_page_ids'] : [];
    $routes_paths = is_array($opt['routes_paths'] ?? null) ? $opt['routes_paths'] : [];

    $route_keys = ['login', 'register', 'lostpassword', 'lostpassword_confirm', 'landing'];
    $out = [];

    foreach ($langs as $lang) {
      $out[$lang] = [];

      foreach ($route_keys as $key) {
        $page_id = (int)($routes_ids[$lang][$key] ?? 0);
        $configured_path = trim((string)($routes_paths[$lang][$key] ?? ''));

        $expected = custausu_support_report_expected_template_for_route($key);
        $actual = '';
        $title = '';
        $permalink = '';
        $path = '';
        $exists = false;

        if ($page_id > 0) {
          $post = get_post($page_id);
          if ($post instanceof WP_Post && $post->post_type === 'page') {
            $exists = true;
            $title = get_the_title($page_id);
            $permalink = (string)get_permalink($page_id);
            $path = function_exists('custausu_compatibility_normalize_path')
              ? custausu_compatibility_normalize_path($permalink)
              : $permalink;
            $actual = (string)get_page_template_slug($page_id);
            if ($actual === '') $actual = 'default';
          }
        }

        $template_ok = ($expected === '' || $actual === $expected);

        $status = 'not_configured';
        if ($page_id > 0 && !$exists) {
          $status = 'page_missing';
        } elseif ($page_id > 0 && $exists && !$template_ok) {
          $status = 'template_mismatch';
        } elseif ($page_id > 0 && $exists && $template_ok) {
          $status = 'ok';
        } elseif ($configured_path !== '') {
          $status = 'path_only';
        }

        $out[$lang][$key] = [
          'page_id' => $page_id,
          'page_exists' => $exists,
          'title' => $title,
          'permalink' => $permalink,
          'path' => $path,
          'configured_path' => $configured_path,
          'expected_template' => $expected,
          'actual_template' => $actual,
          'template_ok' => $template_ok,
          'status' => $status,
        ];
      }
    }

    return $out;
  }
}

if (!function_exists('custausu_support_report_email_template_summary')) {
  function custausu_support_report_email_template_summary(array $email_tpl): array {
    $required_tokens = [
      'verify_register' => ['{{verify_link}}'],
      'verify_resend' => ['{{verify_link}}'],
      'welcome' => [],
    ];

    $out = [];

    foreach ($email_tpl as $lang => $templates) {
      $lang = sanitize_key((string)$lang);
      if ($lang === '' || !is_array($templates)) continue;

      $out[$lang] = [];

      foreach ($templates as $template_key => $row) {
        if (!is_array($row)) continue;

        $template_key = sanitize_key((string)$template_key);
        if ($template_key === '') continue;

        $subject = (string)($row['subject'] ?? '');
        $body = (string)($row['body'] ?? '');

        $missing = [];
        foreach (($required_tokens[$template_key] ?? []) as $token) {
          if (strpos($body, $token) === false) {
            $missing[] = $token;
          }
        }

        $out[$lang][$template_key] = [
          'subject_present' => trim($subject) !== '',
          'body_present' => trim($body) !== '',
          'body_length' => strlen($body),
          'required_tokens' => $required_tokens[$template_key] ?? [],
          'missing_required_tokens' => $missing,
        ];
      }
    }

    return $out;
  }
}

if (!function_exists('custausu_support_report_settings_summary')) {
  function custausu_support_report_settings_summary(array $settings): array {
    $protected_paths = function_exists('custausu_compatibility_collect_protected_paths')
      ? custausu_compatibility_collect_protected_paths()
      : [];

    return [
      'routes_default_lang' => sanitize_key(
        (string)($settings['routes_default_lang'] ?? '')
      ),
      'protected_paths_count' => count($protected_paths),
      'protected_paths' => $protected_paths,
      'logout_redirects' => is_array($settings['routes_logout_redirect'] ?? null)
        ? $settings['routes_logout_redirect']
        : [],
      'auth_theme_present' => !empty($settings['auth_theme'])
        && is_array($settings['auth_theme']),
      'email_theme_present' => !empty($settings['email_theme'])
        && is_array($settings['email_theme']),
      'email_templates' => custausu_support_report_email_template_summary(
        is_array($settings['email_tpl'] ?? null)
          ? $settings['email_tpl']
          : []
      ),
      'keep_data_on_uninstall' => !empty($settings['keep_data_on_uninstall']),
    ];
  }
}

if (!function_exists('custausu_support_report_health_check_snapshot')) {
  function custausu_support_report_health_check_snapshot(): array {
    if (!function_exists('custausu_admin_health_check_run')) {
      return [
        'available' => false,
        'counts' => [],
        'checks' => [],
      ];
    }

    $T = static function(string $en, string $it = ''): string {
      return $en;
    };

    $checks = custausu_admin_health_check_run($T);
    $counts = [
      'ok' => 0,
      'warn' => 0,
      'err' => 0,
      'info' => 0,
      'preview' => 0,
    ];

    $safe_checks = [];

    foreach ((array)$checks as $check) {
      if (!is_array($check)) continue;

      $sev = sanitize_key((string)($check['sev'] ?? 'info'));
      if (!isset($counts[$sev])) $sev = 'info';
      $counts[$sev]++;

      $safe_checks[] = [
        'group' => sanitize_key((string)($check['group'] ?? '')),
        'key' => sanitize_key((string)($check['key'] ?? '')),
        'severity' => $sev,
        'reason' => sanitize_key((string)($check['reason'] ?? '')),
        'label' => (string)($check['label'] ?? ''),
        'value' => (string)($check['value'] ?? ''),
        'hint' => (string)($check['hint'] ?? ''),
      ];
    }

    return [
      'available' => true,
      'counts' => $counts,
      'checks' => $safe_checks,
    ];
  }
}

if (!function_exists('custausu_support_report_rest_probe')) {
  function custausu_support_report_rest_probe(string $url): array {
    $response = wp_remote_get($url, [
      'timeout' => 6,
      'redirection' => 2,
    ]);

    $path = function_exists('custausu_compatibility_normalize_cache_rule')
      ? custausu_compatibility_normalize_cache_rule($url)
      : $url;

    if (is_wp_error($response)) {
      return [
        'path' => $path,
        'reachable' => false,
        'json_valid' => false,
        'code' => 0,
        'reason' => $response->get_error_code(),
      ];
    }

    $code = (int)wp_remote_retrieve_response_code($response);
    $body = (string)wp_remote_retrieve_body($response);
    $decoded = json_decode($body, true);

    return [
      'path' => $path,
      'reachable' => $code > 0 && $code < 500,
      'json_valid' => is_array($decoded),
      'code' => $code,
      'reason' => is_array($decoded) ? 'json' : ($body === '' ? 'empty_body' : 'invalid_json'),
    ];
  }
}

if (!function_exists('custausu_support_report_rest_snapshot')) {
  function custausu_support_report_rest_snapshot(): array {
    return [
      'local_pretty_index' => custausu_support_report_rest_probe(rest_url()),
      'local_fallback_index' => custausu_support_report_rest_probe(home_url('/?rest_route=/')),
    ];
  }
}

if (!function_exists('custausu_support_report_filesystem_snapshot')) {
  function custausu_support_report_filesystem_snapshot(): array {
    $uploads = wp_upload_dir(null, false);
    $uploads_dir = is_array($uploads) ? (string)($uploads['basedir'] ?? '') : '';

    $custausu_logs = custausu_support_report_logs_dir();

    return [
      'uploads_dir_present' => $uploads_dir !== '' && is_dir($uploads_dir),
      'uploads_dir_writable' => $uploads_dir !== '' && is_dir($uploads_dir) && wp_is_writable($uploads_dir),
      'cas_logs_dir_present' => is_dir($custausu_logs),
      'cas_logs_dir_writable' => is_dir($custausu_logs) && wp_is_writable($custausu_logs),
      'plugin_dir_readable' => defined('CUSTAUSU_PLUGIN_DIR') && is_dir(CUSTAUSU_PLUGIN_DIR) && is_readable(CUSTAUSU_PLUGIN_DIR),
    ];
  }
}

if (!function_exists('custausu_support_report_cron_snapshot')) {
  function custausu_support_report_cron_snapshot(): array {
    return [
      'disable_wp_cron' => defined('DISABLE_WP_CRON') && DISABLE_WP_CRON,
      'alternate_wp_cron' => defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON,
    ];
  }
}

if (!function_exists('custausu_support_report_safety_snapshot')) {
  function custausu_support_report_safety_snapshot(): array {
    $available = function_exists('custausu_safe_mode_is_enabled');
    $enabled = $available && custausu_safe_mode_is_enabled();
    $forced = function_exists('custausu_safe_mode_is_forced') && custausu_safe_mode_is_forced();
    $source = function_exists('custausu_safe_mode_source') ? custausu_safe_mode_source() : 'unknown';
    $reason = ($enabled && function_exists('custausu_safe_mode_reason')) ? custausu_safe_mode_reason() : '';
    $force_constant = function_exists('custausu_safe_mode_force_constant_name')
      ? custausu_safe_mode_force_constant_name()
      : 'CUSTAUSU_SAFE_MODE_FORCE';

    $option_state = function_exists('custausu_safe_mode_option_state')
      ? custausu_safe_mode_option_state()
      : [];

    $option_state = is_array($option_state) ? $option_state : [];

    return [
      'safe_mode_available' => $available,
      'safe_mode_enabled' => $enabled,
      'safe_mode_forced_by_wp_config' => $forced,
      'safe_mode_source' => $source,
      'safe_mode_reason' => $reason,
      'protected_paths_fallback' => $enabled ? 'native_wp_login' : 'cas_default_flow',
      'wp_config_recovery_constant' => $force_constant,
      'option_state' => [
        'present' => !empty($option_state),
        'enabled_at_utc' => (string)($option_state['enabled_at_utc'] ?? ''),
        'reason' => (string)($option_state['reason'] ?? ''),
        'enabled_by_user_id_present' => isset($option_state['enabled_by']),
      ],
    ];
  }
}

if (!function_exists('custausu_support_report_recovery_snapshot')) {
  function custausu_support_report_recovery_snapshot(array $compatibility = []): array {
    $recovery = is_array($compatibility['recovery_readiness'] ?? null)
      ? $compatibility['recovery_readiness']
      : [];

    if ($recovery) {
      return $recovery;
    }

    return function_exists('custausu_compatibility_recovery_readiness')
      ? custausu_compatibility_recovery_readiness()
      : [
          'status' => 'unknown',
          'safe_mode' => [
            'available' => function_exists('custausu_safe_mode_is_enabled'),
            'enabled' => function_exists('custausu_safe_mode_is_enabled') && custausu_safe_mode_is_enabled(),
            'forced_by_wp_config' => function_exists('custausu_safe_mode_is_forced') && custausu_safe_mode_is_forced(),
            'wp_config_constant' => function_exists('custausu_safe_mode_force_constant_name')
              ? custausu_safe_mode_force_constant_name()
              : 'CUSTAUSU_SAFE_MODE_FORCE',
          ],
          'rollback' => [
            'automatic_rollback_enabled' => false,
          ],
        ];
  }
}


if (!function_exists('custausu_support_report_cas_state')) {
  function custausu_support_report_cas_state(): array {
    $settings = get_option('custausu_global_settings', []);
    $settings = is_array($settings) ? $settings : [];
    $package_state = function_exists('custausu_free_package_runtime_context')
      ? custausu_free_package_runtime_context()
      : [];
    $package_state = is_array($package_state) ? $package_state : [];

    $tables = [];
    if (function_exists('custausu_db_table')) {
      $table = (string)custausu_db_table('email_verifications');
      $tables['email_verifications'] = [
        'table' => $table,
        'present' => false,
      ];
      if ($table !== '') {
        global $wpdb;
        $found = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table));
        $tables['email_verifications']['present'] = ($found === $table);
      }
    }

    return [
      'settings_summary' => custausu_support_report_settings_summary($settings),
      'routes_snapshot' => custausu_support_report_routes_snapshot(),
      'installed_package_context' => custausu_support_report_redact(
        $package_state,
        'installed_package_context'
      ),
      'db_tables' => $tables,
    ];
  }
}

if (!function_exists('custausu_support_report_generate')) {
  function custausu_support_report_generate(): array {
    global $wp_version;

    $compatibility = function_exists('custausu_compatibility_scan')
      ? custausu_compatibility_scan()
      : [
          'schema_version' => 1,
          'generated_at_utc' => gmdate('Y-m-d H:i:s'),
          'items' => [],
          'counts' => [],
          'cache_guidance' => [],
        ];

    return [
      'schema_version' => 3,
      'product' => 'Custom Auth Suite',
      'generated_at_utc' => gmdate('Y-m-d H:i:s'),
      'support_readiness' => is_array($compatibility['support_readiness'] ?? null) ? $compatibility['support_readiness'] : [],
      'safety_recovery' => function_exists('custausu_support_report_safety_snapshot') ? custausu_support_report_safety_snapshot() : [],
      'recovery_readiness' => function_exists('custausu_support_report_recovery_snapshot') ? custausu_support_report_recovery_snapshot($compatibility) : [],
      'change_history' => function_exists('custausu_compatibility_doctor_change_history') ? custausu_compatibility_doctor_change_history() : [],
      'site' => [
        'home_url' => home_url('/'),
        'site_url' => site_url('/'),
        'is_ssl' => is_ssl(),
        'environment_type' => function_exists('wp_get_environment_type') ? wp_get_environment_type() : 'unknown',
        'locale' => get_locale(),
        'user_locale' => function_exists('get_user_locale') ? get_user_locale() : get_locale(),
        'timezone' => wp_timezone_string(),
        'multisite' => is_multisite(),
        'permalink_structure' => (string)get_option('permalink_structure', ''),
      ],
      'wordpress' => [
        'version' => (string)$wp_version,
        'debug' => defined('WP_DEBUG') && WP_DEBUG,
        'script_debug' => defined('SCRIPT_DEBUG') && SCRIPT_DEBUG,
        'memory_limit' => defined('WP_MEMORY_LIMIT') ? (string)WP_MEMORY_LIMIT : '',
        'max_memory_limit' => defined('WP_MAX_MEMORY_LIMIT') ? (string)WP_MAX_MEMORY_LIMIT : '',
      ],
      'php' => [
        'version' => PHP_VERSION,
        'version_id' => defined('PHP_VERSION_ID') ? PHP_VERSION_ID : 0,
        'sapi' => PHP_SAPI,
        'memory_limit' => ini_get('memory_limit'),
        'max_execution_time' => ini_get('max_execution_time'),
        'upload_max_filesize' => ini_get('upload_max_filesize'),
        'post_max_size' => ini_get('post_max_size'),
      ],
      'database' => custausu_support_report_db_info(),
      'theme' => custausu_support_report_theme_info(),
      'plugin_inventory' => custausu_support_report_plugin_inventory(),
      'filesystem' => custausu_support_report_filesystem_snapshot(),
      'cron' => custausu_support_report_cron_snapshot(),
      'rest' => custausu_support_report_rest_snapshot(),
      'cas_build' => custausu_support_report_build_info(),
      'cas_state' => custausu_support_report_cas_state(),
      'health_check' => custausu_support_report_health_check_snapshot(),
      'compatibility' => $compatibility,
    ];
  }
}