<?php

// 20261109修改：首页整页阶段耗时临时诊断，采样结束后移除。
$GLOBALS['j3_home_profile'] = array(
	'enabled' => isset($_GET['j3homeprof']) && is_string($_GET['j3homeprof']) && $_GET['j3homeprof'] === '1',
	'start'   => microtime(true),
	'marks'   => array(),
	'notes'   => array(),
	'home'    => false,
	'request' => null,
);

function j3_home_profile_mark($name) {
	if (empty($GLOBALS['j3_home_profile']['enabled'])) {
		return;
	}

	$GLOBALS['j3_home_profile']['marks'][$name] = microtime(true);
}

function j3_home_profile_note($name, $value) {
	if (empty($GLOBALS['j3_home_profile']['enabled'])) {
		return;
	}

	$GLOBALS['j3_home_profile']['notes'][$name] = $value;
}

function j3_home_profile_shutdown() {
	$profile = $GLOBALS['j3_home_profile'] ?? null;

	if (!$profile || empty($profile['enabled']) || empty($profile['home'])) {
		return;
	}

	j3_home_profile_mark('shutdown_begin');

	$marks = $GLOBALS['j3_home_profile']['marks'];
	asort($marks, SORT_NUMERIC);

	$current = $GLOBALS['j3_home_profile']['start'];
	$last = $current;
	$lines = array();

	foreach ($marks as $name => $time) {
		$lines[] = sprintf(
			"phase | request=%s | name=%s | delta_ms=%.3f | elapsed_ms=%.3f\n",
			$GLOBALS['j3_home_profile']['request'],
			$name,
			($time - $current) * 1000,
			($time - $GLOBALS['j3_home_profile']['start']) * 1000
		);

		$current = $time;
		$last = $time;
	}

	$notes = $GLOBALS['j3_home_profile']['notes'];
	$summary = sprintf(
		"summary | request=%s | route=common/home | script_total_ms=%.3f | peak_memory_mb=%.2f | output_bytes=%d | compressed_bytes=%d | compression_level=%s | php=%s\n",
		$GLOBALS['j3_home_profile']['request'],
		($last - $GLOBALS['j3_home_profile']['start']) * 1000,
		memory_get_peak_usage(true) / 1048576,
		(int)($notes['output_bytes'] ?? 0),
		(int)($notes['compressed_bytes'] ?? 0),
		(string)($notes['compression_level'] ?? ''),
		PHP_VERSION
	);

	$log_file = defined('DIR_LOGS') ? DIR_LOGS . 'j3_home_profile.log' : __DIR__ . '/storage/logs/j3_home_profile.log';

	@file_put_contents($log_file, $summary . implode('', $lines), FILE_APPEND | LOCK_EX);
}

if ($GLOBALS['j3_home_profile']['enabled']) {
	$GLOBALS['j3_home_profile']['request'] = date('YmdHis') . '-' . str_replace('.', '', uniqid('', true));
	register_shutdown_function('j3_home_profile_shutdown');
	j3_home_profile_mark('index_start');
}

// Version
define('VERSION', '3.0.5.1');

// Configuration
if (is_file('config.php')) {
	/** @phpstan-ignore-next-line requireOnce.fileNotFound */
	require_once('config.php');
}

// Install
if (!defined('DIR_APPLICATION')) {
	header('Location: install/index.php');
	exit;
}

// Startup
require_once(DIR_SYSTEM . 'startup.php');

start('catalog');
