<?php

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

/**
 * Native integrations for page-cache plugins used alongside Niwa AI.
 */
class Niwa_AI_External_Page_Cache {

	/** @var bool */
	private static $seraphinite_refreshed = false;

	/**
	 * Delete Seraphinite Accelerator's active cache and queue its Cleanup old job.
	 *
	 * @param bool $force Allow an explicit tool call to run again in the same request.
	 * @return array<string, mixed>
	 */
	public static function refresh_seraphinite( $force = false ) {
		if ( self::$seraphinite_refreshed && ! $force ) {
			return array(
				'success'    => true,
				'detected'   => true,
				'refreshed'  => true,
				'deduplicated' => true,
			);
		}

		if ( ! class_exists( '\\seraph_accel\\API' ) || ! is_callable( array( '\\seraph_accel\\API', 'OperateCache' ) ) ) {
			return array(
				'success'   => true,
				'detected'  => false,
				'refreshed' => false,
			);
		}

		self::$seraphinite_refreshed = true;

		try {
			$delete_result  = \seraph_accel\API::OperateCache( \seraph_accel\API::CACHE_OP_DEL );
			$cleanup_result = \seraph_accel\API::OperateCache( \seraph_accel\API::CACHE_OP_CLEAR );
		} catch ( \Throwable $e ) {
			return array(
				'success'   => false,
				'detected'  => true,
				'refreshed' => false,
				'error'     => $e->getMessage(),
			);
		}

		if ( false === $delete_result || false === $cleanup_result ) {
			return array(
				'success'         => false,
				'detected'        => true,
				'refreshed'       => false,
				'delete_queued'   => false !== $delete_result,
				'cleanup_queued'  => false !== $cleanup_result,
				'error'           => 'Seraphinite Accelerator nije prihvatio oba cache posla.',
			);
		}

		return array(
			'success'        => true,
			'detected'       => true,
			'refreshed'      => true,
			'delete_queued'  => true,
			'cleanup_queued' => true,
		);
	}

	/**
	 * Best-effort automatic refresh that never changes the write tool result.
	 *
	 * @param string $context Tool or runner that caused the refresh.
	 * @return array<string, mixed>
	 */
	public static function refresh_seraphinite_after_change( $context = '' ) {
		$result = self::refresh_seraphinite();
		if ( empty( $result['success'] ) ) {
			error_log( '[Niwa AI] Seraphinite cache refresh failed' . ( '' !== $context ? ' after ' . $context : '' ) . ': ' . ( isset( $result['error'] ) ? $result['error'] : 'unknown error' ) );
		}

		return $result;
	}
}
