<?php
/**
 * Aggregates model token usage for agent-loop runs.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Agent_Token_Usage {

	public static function accumulate( &$total_usage, $usage ) {
		if ( ! is_array( $usage ) ) {
			return;
		}

		foreach ( array( 'prompt_tokens', 'completion_tokens', 'total_tokens', 'cached_tokens' ) as $key ) {
			if ( ! isset( $total_usage[ $key ] ) ) {
				$total_usage[ $key ] = 0;
			}
			$total_usage[ $key ] += isset( $usage[ $key ] ) ? max( 0, intval( $usage[ $key ] ) ) : 0;
		}

		$prompt = isset( $total_usage['prompt_tokens'] ) ? intval( $total_usage['prompt_tokens'] ) : 0;
		$cached = isset( $total_usage['cached_tokens'] ) ? intval( $total_usage['cached_tokens'] ) : 0;
		$total_usage['cache_hit_rate'] = $prompt > 0 ? round( min( $cached, $prompt ) / $prompt, 4 ) : 0.0;
	}
}
