<?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='qwen/qwen3-coder-30b'>
    </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=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;
                $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;
    }
}

