<?php
/**
 * PHPUnit + WP test environment bootstrap.
 *
 * @package Ppok\AIToolkit\Tests
 * @license GPL-2.0-or-later
 *
 * Boot sequence:
 *   1. Install the SQLite drop-in into vendor/wordpress/wp-content/db.php.
 *   2. Tell wp-phpunit to use our tests/wp-tests-config.php.
 *   3. Load wp-phpunit's functions (gives us tests_add_filter).
 *   4. Hook our plugin in at muplugins_loaded, run its activator once WP is up.
 *   5. Hand off to wp-phpunit's bootstrap to install WP + load the test framework.
 */

$plugin_root = dirname( __DIR__ );
$wp_root     = $plugin_root . '/vendor/wordpress';
$wp_tests    = $plugin_root . '/vendor/wp-phpunit/wp-phpunit';
$wp_content  = $wp_root . '/wp-content';

if ( ! is_dir( $wp_root ) ) {
	fwrite( STDERR, "WordPress not found at {$wp_root}. Run `composer install`.\n" );
	exit( 1 );
}

if ( ! is_dir( $wp_tests ) ) {
	fwrite( STDERR, "wp-phpunit not found at {$wp_tests}. Run `composer install`.\n" );
	exit( 1 );
}

// 1. Install SQLite drop-in.
if ( ! is_dir( $wp_content ) ) {
	mkdir( $wp_content, 0755, true );
}
$dropin_src  = __DIR__ . '/_helpers/sqlite-db.php';
$dropin_dest = $wp_content . '/db.php';
if ( ! file_exists( $dropin_dest ) || md5_file( $dropin_src ) !== md5_file( $dropin_dest ) ) {
	copy( $dropin_src, $dropin_dest );
}

// 2. Point wp-phpunit at our config.
if ( ! defined( 'WP_TESTS_CONFIG_FILE_PATH' ) ) {
	define( 'WP_TESTS_CONFIG_FILE_PATH', __DIR__ . '/wp-tests-config.php' );
}

// 3. Load the test framework functions (gives us tests_add_filter).
require_once $wp_tests . '/includes/functions.php';

// 4. Register the plugin to load + activate during WP boot.
tests_add_filter(
	'muplugins_loaded',
	static function () use ( $plugin_root ) {
		require $plugin_root . '/ppok-ai-toolkit.php';
		\Ppok\AIToolkit\Activator::activate();
	}
);

// 5. Boot WP + the test framework.
require $wp_tests . '/includes/bootstrap.php';
