<?php

namespace Shm\ShmRPC\ShmRPCCodeGen;

use Shm\ShmRPC\ShmRPCCodeGen\CodeGenPhp\CodeGenPhp;
use Shm\ShmUtils\ShmInit;
use Shm\ShmUtils\ShmTwig;

class ShmRPCCodeGen
{

    public static array $tsTypes = [];


    public static function php(array $schema)
    {
        $phpCode = CodeGenPhp::php($schema);
        echo $phpCode;
    }



    public static function html(array $schema, $json = false)
    {




        $requestsData = [];

        $linkRequest = [];

        $keysGraph = [];
        foreach ($schema  as $key => $field) {


            if ($_GET['method'] ?? null) {
                if ($key !== $_GET['method']) {
                    continue;
                }
            }



            $ignore = $field['ignore'] ?? false;
            if ($ignore) {

                continue;
            }



            $requestsData[$key] = (new ShmRPCRequestCode($field['type'], $field['args'] ?? null, $key, $field['formData'] ?? null))->initialize();

            $linkRequest[$key] = "export const " . $key . " = rpc." . $key . ";";
        }


        ksort(TSType::$tsTypes);
        ksort($requestsData);



        $allTypesKeys = array_keys(TSType::$tsTypes);

        $types = implode("\n", array_values(TSType::$tsTypes));

        $requestsAll =   array_values($requestsData);
        $linkRequest = array_values($linkRequest);


        $requests = [
            "import type { RpcResponse, " . implode(',', $allTypesKeys) . " } from './types';",


            "import { debounce, map } from 'lodash';",
            "import { observable, toJS } from 'mobx';"

        ];

        if (isset($_GET['rn'])) {

            $requests[] = "import { fromByteArray, toByteArray } from 'react-native-quick-base64';";
            $requests[] = "import { Buffer } from 'buffer';";
        }


        $requests = [
            ...$requests,

            'export const rpc = {',
            ...$requestsAll,
            '};',
            ...$linkRequest,
        ];

        // Загружаем код rpcClient из отдельного файла

        if (isset($_GET['rn'])) {
            $rpcClientPath = __DIR__ . '/rpcClient_rn.ts';
        } else {
            $rpcClientPath = __DIR__ . '/rpcClient.ts';
        }


        $rpcClientCode = file_get_contents($rpcClientPath);
        $requests[] = $rpcClientCode;



        $requests[] = ShmRPCCodeGenExtensionsStore::tsClass();



        $requests[] = 'export const enumHelper = ' . json_encode(TSType::$enumHelperCode, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

        $requests[] = "export const enumHelperValue = (
   values: { [key: string]: string },
   key: string | undefined | null,
   defaultValue: any
) => {
   if (!key) return defaultValue;
   return values[key!] ?? defaultValue;
}";


        $requests = implode("\n", $requests);

        $files = [];

        if (($_SERVER['SERVER_NAME'] ?? null) == "localhost") {
            /**
             * Если есть ShmInit::$rootDir . '/schema_history/' то удаляем эту директорию
             * это удаление старых лог файлов, которые не показали свою эффективность
             * Удаляем включая саму директорию schema_history
             */

            $dir =  ShmInit::$rootDir . '/schema_history';
            if (is_dir($dir)) {
                rmdir($dir);
            }




            /*
            $REQUEST_URI = $_SERVER['REQUEST_URI'];

            //Убарем GET параметры
            $REQUEST_URI = explode('?', $REQUEST_URI)[0];
            //Все / заменяем на _
            $REQUEST_URI = str_replace('/', '_', $REQUEST_URI);


            $dir =  ShmInit::$rootDir . '/schema_history/' . $REQUEST_URI;

*/
            /*

            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }

            $dirTypes = $dir . '/types';
            if (!is_dir($dirTypes)) {
                mkdir($dirTypes, 0777, true);
            }

            $dirRequests = $dir . '/requests';
            if (!is_dir($dirRequests)) {
                mkdir($dirRequests, 0777, true);
            }


            foreach (TSType::$tsTypes as $key => $type) {

                file_put_contents($dirTypes . '/' . $key . '.tmp', $type);
            }

            foreach ($requestsData as $key => $request) {
                file_put_contents($dirRequests . '/' . $key . '.tmp', $request);
            }
                */
        }

        $types = "export interface RpcError {
  type: 'UNAUTHORIZED' | 'VALIDATION_ERROR' | 'NOT_FOUND' | 'INTERNAL_ERROR' | 'FORBIDDEN' | 'RATE_LIMITED' | string;
  message: string;
  code?: number;
}

export interface RpcResponse<T = unknown, Extensions = unknown> {
  datetime: number;
  success: boolean;
  result: T | null;
  extensions: Extensions | null;
  error: RpcError | null;
}" . "\n\n" . $types;



        if ($json) {

            echo json_encode([
                'types' => $types,
                'requests' => $requests
            ]);
            exit;
        }


        header('Content-Type: text/html; charset=utf-8');

        // Escape backticks for JavaScript template literals
        $typesEscaped = str_replace('`', '\`', $types);
        $requestsEscaped = str_replace('`', '\`', $requests);

        echo ShmTwig::render('@shm/codegen', [
            'types' => $typesEscaped,
            'requests' => $requestsEscaped,
        ]);

        exit;
    }
}