<?php

declare(strict_types=1);

namespace kodorvan\neurobot\models;

// Files of the project
use kodorvan\neurobot\models\core,
	kodorvan\neurobot\models\enumerations\tariff as tariff_type;

// Svoboda time
use svoboda\time\statement as svoboda;

// Baza database
use mirzaev\baza\database,
	mirzaev\baza\column,
	mirzaev\baza\record,
	mirzaev\baza\enumerations\encoding,
	mirzaev\baza\enumerations\type;

// Library for neural networks support
use mirzaev\neuroseti\network,
	mirzaev\neuroseti\api;

// Active Record pattern
use mirzaev\record\interfaces\record as record_interface,
	mirzaev\record\traits\record as record_trait;

// Port of the fast BPE tokeniser for OpenAI
use Yethee\Tiktoken\EncoderProvider as tiktoken;

// Built-in libraries
use Exception as exception,
	RuntimeException as exception_runtime;

/**
 * Tariff
 *
 * @package kodorvan\neurobot\models
 *
 * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
final class tariff extends core implements record_interface
{
	use record_trait;

	/**
	 * File
	 *
	 * @var string $database Path to the database file
	 */
	protected string $file = DATABASES . DIRECTORY_SEPARATOR . 'tariffs.baza';

	/**
	 * Database
	 *
	 * @var database $database The database
	 */
	public protected(set) database $database;

	/**
	 * Serialized
	 *
	 * @var bool $serialized Is the implementator object serialized?
	 */
	private bool $serialized = true;

	/**
	 * Constructor
	 *
	 * identifier - The record identifier
	 * account - The account identifier
	 * invoice - The invoice identifier
	 * type - The tariff type
	 * tokens - Amount of the tariff tokens (independed copy)
	 * used - Amount of used the tarif tokens
	 * updated - Date of the last the record updation
	 * created - Date of the record creation
	 *
	 * @method record|null $record The record
	 *
	 * @return void
	 */
	public function __construct(?record $record = null)
	{
		// Initializing the database
		$this->database = new database()
			->encoding(encoding::utf8)
			->columns(
				new column('identifier', type::long_long_unsigned),
				new column('account', type::long_long_unsigned),
				new column('invoice', type::long_long_unsigned),
				new column('type', type::string, ['length' => 16]),
				new column('tokens', type::integer_unsigned),
				new column('used', type::integer_unsigned),
				new column('active', type::char),
				new column('updated', type::integer_unsigned),
				new column('created', type::integer_unsigned)
			)
			->connect($this->file);

		// Initializing the record
		$record instanceof record and $this->record = $record;
	}

	/**
	 * Write
	 *
	 * @param int $account The account identifier (0 - empty)
	 * @param int $invoice The invoice identifier (0 - empty)
	 * @param tariff_type $type The tariff
	 * @param bool $active Is the tariff active?
	 *
	 * @return record|false The record, if created
	 */
	public function write(
		int $account = 0,
		int $invoice = 0,
		tariff_type $type = TARIFF_DEFAULT ?? tariff_type::free,
		bool $active = true
	): record|false {
		$record = $this->database->record(
			$this->database->count() + 1,
			$account,
			$invoice,
			$type->name,
			match ($type) {
				tariff_type::endless => 0,
				default => $type->tokens() ?? 0
			},
			0,
			(int) $active,
			svoboda::timestamp(),
			svoboda::timestamp()
		);

		// Writing the record into the database
		$created = $this->database->write($record);

		// Exit (success)
		return $created ? $record : false;
	}

	/**
	 * Serialize
	 *
	 * @return self The instance from which the method was called (fluent interface)
	 */
	public function serialize(): self
	{
		if ($this->serialized) {
			// The record implementor is serialized

			// Exit (fail)
			throw new exception_runtime('The record implementator object is already serialized');
		}

		// Serializing the record parameters
		$this->record->type = $this->record->type->name;

		// Writing the serializing status
		$this->serialized = true;

		// Exit (success)
		return $this;
	}

	/**
	 * Deserialize
	 *
	 * @return self The instance from which the method was called (fluent interface)
	 */
	public function deserialize(): self
	{
		if (!$this->serialized) {
			// The record implementor is deserialized

			// Exit (fail)
			throw new exception_runtime('The record implementator object is already deserialized');
		}

		// Deserializing the record parameters
		$this->record->type = tariff_type::{$this->record->type} ?? TARIFF_DEFAULT ?? tariff_type::free;

		// Writing the serialized status
		$this->serialized = false;

		// Exit (success)
		return $this;
	}

	/**
	 * Tokens
	 *
	 * Calculate tokens of the text
	 *
	 * @param string $text The text
	 * @param network $network The neural network
	 *
	 * @return int Amount of tokens
	 *
	 * @deprecated VERY SLOW
	 */
	public static function tokens(string $text, network $network): ?int
	{
		// Calculating and exit (success/fail) 
		return count(new tiktoken()->getForModel($network->value)->encode($text));
	}

	/**
	 * Priority
	 *
	 * Search for the most priority tariff for the account
	 *
	 * @param int $account The account identifier
	 *
	 * @return selfnull The most priority tariff
	 */
	public function priority(int $account): ?self
	{
		// Search for the account tariff
		$tariffs = new tariff()->database->read(
			filter: fn(record $record) =>
			$record->account === $account
				&& $record->active === 1
				&& $record->used <= $record->tokens,
			amount: 10
		);

		var_dump($tariffs);

		if (count($tariffs) > 0) {
			// Found at least 1 tariff

			usort(
				$tariffs,
				function ($a, $b) {
					try {
						$a_priority = tariff_type::{$a['type']}->priority();
						$b_priority = tariff_type::{$b['type']}->priority();

						if ($a_priority > $b_priority) return 1;
						else if ($a_priority < $b_priority) return -1;
						else {
							$a_updated = $a['updated'];
							$b_updated = $b['updated'];

							if ($a_updated > $b_updated) return 1;
							else if ($a_updated < $b_updated) return -1;
						}

						return 0;
					} catch (exception $exception) {
					}

					return 0;
				}
			);

			var_dump($tariffs);
			die;
		}

		// Exit (fail)
		return null;
	}
}
