<?php

$cms["modules"]["ai.mod.php"] = array(
    "name"        => "ai_module_name",
    "description" => "ai_module_description",
    "files"       => array(
        ".cms/mod/ai.mod.php",
        ".cms/js/ai.js",
        ".cms/css/ai.less",
        ".cms/css/ai.css",
        ".cms/lang/ru_RU.UTF-8/ai.mod.php",
        ".cms/lang/en_US.UTF-8/ai.mod.php",
        ".cms/lang/uk_UA.UTF-8/ai.mod.php",
    ),
);

// ---------------------------------------------------------------------
//  Ничего не делаем, если модуль отключён в конфиге
// ---------------------------------------------------------------------
if ( ! empty( $cms["config"]["ai.mod.php"]["disabled"] ) ) {
    return;
}

// ---------------------------------------------------------------
//  Регистрация хуков
// ---------------------------------------------------------------
if ( is_admin() ) {
    hook_add_fn( "admin_header",   "cms_ai_head" );
    hook_add_fn( "admin",          "cms_ai_page" );
    hook_add_fn( "api",            "cms_ai_api" );
}

// ---------------------------------------------------------------------
//  Хук admin_header – подключаем стили и скрипты админки
// ---------------------------------------------------------------------
function cms_ai_head() {
    global $cms;
    if ( is_admin_header_on( "ai.mod.php" ) ) {
        echo "        <link rel=stylesheet href='{$cms["base_path"]}css/ai.css'>\n";
        echo "        <script src='{$cms["base_path"]}js/ai.js'></script>\n";
    }
}

// ---------------------------------------------------------------------
//  Страница настроек модуля в админке
// ---------------------------------------------------------------------
function cms_ai_page() {
    global $cms;

    if ( is_admin_header_on( "ai.mod.php" ) ) {

        #region page
        $page = "
<div class='header panel'>

    <label>
        <span class=title>" . __( "api_endpoint" ) . ":</span>
        <input name=endpoint type=text value='' autocomplete=off size=32 placeholder='http://127.0.0.1:1234/v1/chat/completions'>
    </label>

    <label>
        <span class=title>" . __( "model_name" ) . ":</span>
        <input name=model type=text value='' autocomplete=off size=20 placeholder='google/gemma-4-26b-a4b'>
    </label>
    
    <label>
        <span class=title>" . __( "api_key" ) . ":</span>
        " . widget( "password_widget.php", array( "password" => "", "placeholder" => "" ) ) . "
    </label>

    <button class='save button'>
        <span>" . __( "save" ) . "</span>
    </button>

</div>
<div class=main>
    <div class=chat>

    </div>
    <div class=side>

        <div class='preset select widget'>
            <div class=selected data-preset=''>
                <div class=value></div>
                <div class='icon down button'><span></span></div>
            </div>
            <div class=options>
                <div class=search>
                    <input class=search-field type=text name=search placeholder='" . __( "new_preset" ) . "'>
                </div>
                <div class=scrollable>
                    
                </div>
            </div>
        </div>

        <div>
            <textarea name=prompt placeholder='" . __( "prompt" ) . "'></textarea>
        </div>

        <div>
            <textarea name=files_list placeholder='" . __( "files_list_placeholder" ) . "'></textarea>
        </div>

        <div>
            <textarea name=plan placeholder='" . __( "plan" ) . "'></textarea>
        </div>

    </div>
</div>
<div class='user panel'>
    <textarea name=msg></textarea>
    <div class=buttons>

        <!--
        <button class='copy demo button'>
            <span>" . __( "copy_demo" ) . "</span>
        </button>
        -->

        <button class='button settings icon'>
            <span></span>
        </button>

        <button class='clear button'>
            <span>" . __( "clear" ) . "</span>
        </button>

        <button class='send button'>
            <span>" . __( "send" ) . "</span>
        </button>

        <button class='stop button'>
            <span>" . __( "stop" ) . "</span>
        </button>

    </div>
</div>
";
#endregion page

        // Сохраняем пункт меню, если ещё нет
        if ( empty( $cms["config"]["ai.mod.php"]["menu"]["ai"] ) ) {
            $cms["config"]["ai.mod.php"]["menu"]["ai"] = array(
                "title"   => "ai_module_name",
                "sort"    => 30,
                "section" => "content",
            );
            cms_save_config();
        }

        $cms["admin_pages"]["ai"] = $page;

    }
}

// ---------------------------------------------------------------------
//  API‑обработчик админки
// ---------------------------------------------------------------------
function cms_ai_api() {
    global $cms;

    if ( empty( $_POST["fn"] ) ) { return; }

    switch ( $_POST["fn"] ) {
        case "ai_get_cms_files":
            $files_list = $cms["modules"][ $_POST["mod"] ]["files"];
            $wrapped_files = "";
            $files_count = 0;
            $lines_count = 0;
            foreach ( $files_list as $file ) {
                $p = pathinfo( $file );
                $file_path = $cms["site_dir"] . "/" .$file;
                if ( is_file( $file_path ) ) {
                    $lines_count += count( file( $file_path ) );
                    $content = file_get_contents( $file_path );
                    $wrapped = "```{$p["extension"]} {$file}\n{$content}\n```\n\n";
                    $wrapped_files .= $wrapped;
                    $files_count++;
                }
            }
            echo json_encode( array(
                "result" => array(
                    "content"       => $wrapped_files,
                    "size_in_chars" => mb_strlen( $wrapped_files ),
                    "files_count"   => $files_count,
                    "lines_count"   => $lines_count,
                )
            ) );
        break;

        case "ai_get_files_content":
            $files_list_input = trim( $_POST["files"] );
            if ( empty( $files_list_input ) ) {
                echo json_encode( array(
                    "result" => array(
                        "content" => "",
                        "size_in_chars" => 0,
                        "files_count" => 0,
                    )
                ) );
                break;
            }

            $files_array = preg_split( '/\r?\n/', $files_list_input );
            $wrapped_files = "";
            $files_count = 0;
            $lines_count = 0;

            foreach ( $files_array as $file_path_relative ) {
                $file_path_relative = trim( $file_path_relative );
                if ( empty( $file_path_relative ) ) {
                    continue;
                }

                $file_path = $cms["site_dir"] . "/" . $file_path_relative;
                if ( ! is_file( $file_path ) ) {
                    continue;
                }

                $p = pathinfo( $file_path_relative );
                $lines_count += count( file( $file_path ) );
                $content = file_get_contents( $file_path );
                $wrapped = "```{$p["extension"]} {$file_path_relative}\n{$content}\n```\n\n";
                $wrapped_files .= $wrapped;
                $files_count++;
            }

            echo json_encode( array(
                "result" => array(
                    "content"       => $wrapped_files,
                    "size_in_chars" => mb_strlen( $wrapped_files ),
                    "files_count"   => $files_count,
                    "lines_count"   => $lines_count,
                )
            ) );
        break;
    }
}

