<?php
/**
 * API usage tracking and limits.
 *
 * @package AIAltTextGenerator
 * @since 1.4.0
 */

namespace AIAltTextGenerator;

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

/**
 * Monthly usage counters and cost estimates.
 *
 * @since 1.4.0
 */
class Usage {

	/**
	 * @return array{month: string, generations: int, tokens: int, estimated_cost: float}
	 */
	public static function getSummary(): array {
		$data = get_option( Settings::USAGE_OPTION, [] );
		if ( ! is_array( $data ) ) {
			$data = [];
		}

		$month = gmdate( 'Y-m' );
		if ( ( $data['month'] ?? '' ) !== $month ) {
			return [
				'month'          => $month,
				'generations'    => 0,
				'tokens'         => 0,
				'estimated_cost' => 0.0,
			];
		}

		return [
			'month'          => $month,
			'generations'    => (int) ( $data['generations'] ?? 0 ),
			'tokens'         => (int) ( $data['tokens'] ?? 0 ),
			'estimated_cost' => round( (float) ( $data['estimated_cost'] ?? 0 ), 4 ),
		];
	}

	public static function record( int $tokens, string $model = '' ): void {
		$summary = self::getSummary();
		++$summary['generations'];
		$summary['tokens'] += max( 0, $tokens );
		$summary['estimated_cost'] += self::estimateCost( max( 0, $tokens ), $model );

		update_option(
			Settings::USAGE_OPTION,
			[
				'month'          => $summary['month'],
				'generations'    => $summary['generations'],
				'tokens'         => $summary['tokens'],
				'estimated_cost' => $summary['estimated_cost'],
			],
			false
		);
	}

	public static function isLimitReached(): bool {
		$settings = Settings::get();
		$limit    = FeatureGate::effectiveMonthlyLimit( $settings );

		if ( $limit <= 0 ) {
			return false;
		}

		$summary = self::getSummary();

		return $summary['generations'] >= $limit;
	}

	/**
	 * Rough per-1K token estimate for budgeting (not billing-accurate).
	 */
	private static function estimateCost( int $tokens, string $model ): float {
		$model = Models::sanitize( $model );
		$rates = [
			'gpt-4o-mini'  => 0.0003,
			'gpt-4.1-nano' => 0.0002,
			'gpt-4.1-mini' => 0.0005,
			'gpt-5-mini'   => 0.0006,
			'gpt-5.4-mini' => 0.0007,
			'gpt-4.1'      => 0.002,
			'gpt-4o'       => 0.003,
			'gpt-5.4'      => 0.003,
			'gpt-5.5'      => 0.004,
			'o4-mini'      => 0.002,
		];

		$rate = $rates[ $model ] ?? 0.0004;

		return ( $tokens / 1000 ) * $rate;
	}
}
