<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));
$statusOptions = ai_model_status_options();
$catalogOptions = ai_model_catalog_options();
$error = '';
$success = '';
$recordFound = false;
$testResult = null;
$testError = '';
$testSuccess = '';
$modelId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $modelId = (int)$_POST['id'];
}

$postAction = isset($_POST['action']) ? trim((string)$_POST['action']) : 'save';

$form = array(
    'id' => $modelId,
    'model_name' => '',
    'endpoint_id' => '',
    'api_url' => '',
    'api_key' => '',
    'status' => 'enabled',
    'remark' => ''
);

if ($modelId <= 0) {
    $error = '缺少有效的AI模型ID，无法编辑。';
} else {
    try {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && $postAction === 'save') {
            require_csrf();
            foreach ($form as $key => $value) {
                if ($key === 'id') {
                    continue;
                }
                $form[$key] = isset($_POST[$key]) ? trim((string)$_POST[$key]) : $value;
            }

            if ($form['model_name'] === '' || !isset($catalogOptions[$form['model_name']])) {
                $error = '请选择可用的模型。';
            } elseif (!isset($statusOptions[$form['status']])) {
                $error = '模型状态值无效。';
            } elseif (!filter_var($form['api_url'], FILTER_VALIDATE_URL)) {
                $error = '接口地址格式不正确，请输入完整 URL。';
            } elseif ($form['api_key'] === '' && (!isset($_POST['keep_api_key']) || $_POST['keep_api_key'] !== '1')) {
                $error = '请输入 API Key，或保留当前已保存的 Key。';
            } elseif (!empty($catalogOptions[$form['model_name']]['requires_endpoint_id']) && $form['endpoint_id'] === '') {
                $error = '该模型需要填写接入点ID (Endpoint ID)。';
            } else {
                update_ai_model($modelId, $form);
                $success = 'AI 模型 ' . $catalogOptions[$form['model_name']]['name'] . ' 已更新成功。';
            }
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && $postAction === 'test') {
            require_csrf();
            try {
                $testResult = test_ai_model_by_id($modelId, '');
                if (!empty($testResult['success'])) {
                    $testSuccess = '接口连通性测试通过，模型已正常响应。';
                } else {
                    $testError = $testResult['error_message'] !== '' ? $testResult['error_message'] : '接口已响应但状态异常（HTTP ' . $testResult['http_code'] . '），请检查配置。';
                }
            } catch (Exception $ex) {
                $testError = $ex->getMessage();
            }
        }

        $model = find_ai_model_by_id($modelId);
        if (!$model) {
            $error = '未找到对应的AI模型配置。';
        } else {
            $recordFound = true;
            $form['id'] = (int)$model['id'];
            $form['model_name'] = isset($model['code']) ? $model['code'] : $form['model_name'];
            $form['endpoint_id'] = isset($model['model_name']) ? $model['model_name'] : '';
            $form['api_url'] = isset($model['api_url']) ? $model['api_url'] : $form['api_url'];
            $form['api_key'] = isset($model['api_key']) ? $model['api_key'] : $form['api_key'];
            $form['status'] = isset($model['status']) ? $model['status'] : $form['status'];
            $form['remark'] = isset($model['remark']) ? $model['remark'] : $form['remark'];
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
$catalogJson = json_encode($catalogOptions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 编辑AI模型</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('ai_models', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>编辑AI模型</h1><p>支持 DeepSeek 与火山引擎（豆包）等 OpenAI 兼容模型。</p></div>
                <div class="topbar-actions"><a class="btn-ghost" href="/admin/ai-model/list.php">返回列表</a></div>
            </header>
            <section class="page-card">
                <div class="card-head"><div><h2>模型编辑表单</h2><p>仅允许修改模型、接口地址、密钥与状态，其余参数按官方文档固化。</p></div></div>
                <?php if ($success !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">保存成功</strong>
                        <p style="margin:0; color:#166534;"><?php echo e($success); ?></p>
                    </div>
                <?php endif; ?>
                <?php if ($error !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">操作失败</strong>
                        <p style="margin:0; color:#b91c1c;"><?php echo e($error); ?></p>
                    </div>
                <?php endif; ?>
                <?php if ($recordFound): ?>
                    <form method="post" action="/admin/ai-model/edit.php?id=<?php echo (int)$form['id']; ?>">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">
                        <input type="hidden" name="action" value="save" id="form-action">
                        <div class="form-grid">
                            <div class="input-group"><span>* 模型</span><select class="select" name="model_name" id="sel-model"><option value="">请选择模型</option><?php foreach ($catalogOptions as $key => $item): ?><option value="<?php echo e($key); ?>"<?php echo $form['model_name'] === $key ? ' selected' : ''; ?>><?php echo e($item['name']); ?>（<?php echo e($item['provider']); ?>）</option><?php endforeach; ?></select></div>
                            <div class="input-group"><span>服务商</span><input class="input" type="text" id="txt-provider" value="" readonly></div>
                            <div class="input-group" id="grp-endpoint" style="grid-column: 1 / -1; display:none;"><span>* 接入点ID</span><input class="input" type="text" name="endpoint_id" id="txt-endpoint" value="<?php echo e($form['endpoint_id']); ?>" placeholder="在火山引擎控制台创建推理接入点后获取，如 ep-20240101xxxxx"></div>
                            <div class="input-group" style="grid-column: 1 / -1;"><span>* API地址</span><input class="input" type="text" name="api_url" value="<?php echo e($form['api_url']); ?>"></div>
                            <div class="input-group"><span>状态</span><select class="select" name="status"><?php foreach ($statusOptions as $key => $label): ?><option value="<?php echo e($key); ?>"<?php echo $form['status'] === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option><?php endforeach; ?></select></div>
                            <div class="input-group" style="grid-column: 1 / -1;"><span>API Key</span><input class="input" type="text" name="api_key" value="" placeholder="如不修改可留空"></div>
                            <div class="input-group" style="grid-column: 1 / -1;"><label style="display:flex; gap:8px; align-items:center;"><input type="checkbox" name="keep_api_key" value="1" checked> 保留当前已保存的 API Key（留空时生效）</label></div>
                            <div class="input-group" style="grid-column: 1 / -1;"><span>备注</span><textarea class="input" name="remark" rows="3"><?php echo e($form['remark']); ?></textarea></div>
                        </div>
                        <div class="table-note" style="margin-top:16px;">系统根据所选模型自动固定请求方式（POST）与 OpenAI 兼容请求体；火山引擎模型需额外填写接入点ID。</div>
                        <div class="filter-row" style="margin-top:18px;">
                            <button class="btn-primary" type="submit">保存修改</button>
                            <button class="btn-soft" type="submit" onclick="document.getElementById('form-action').value='test';">测试连通性</button>
                            <a class="btn-ghost" href="/admin/ai-model/list.php">取消</a>
                        </div>
                    </form>
                <?php endif; ?>
            </section>
            <?php if ($testSuccess !== '' || $testError !== '' || $testResult !== null): ?>
                <section class="page-card" style="margin-top:20px;" id="test-result">
                    <div class="card-head"><div><h2>连通性测试结果</h2><p>使用已保存配置发起了一次真实接口请求。</p></div></div>
                    <?php if ($testSuccess !== ''): ?>
                        <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                            <strong style="color:#15803d;">测试通过</strong>
                            <p style="margin:0; color:#166534;"><?php echo e($testSuccess); ?></p>
                        </div>
                    <?php endif; ?>
                    <?php if ($testError !== ''): ?>
                        <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                            <strong style="color:#dc2626;">测试失败</strong>
                            <p style="margin:0; color:#b91c1c;"><?php echo e($testError); ?></p>
                        </div>
                    <?php endif; ?>
                    <?php if ($testResult !== null): ?>
                        <div class="mini-grid" style="margin-bottom:16px;">
                            <div class="mini-item"><strong>HTTP 状态码</strong><p><?php echo (int)$testResult['http_code']; ?></p></div>
                            <div class="mini-item"><strong>调用状态</strong><p><?php echo !empty($testResult['success']) ? '成功' : '失败'; ?></p></div>
                        </div>
                        <div class="input-group" style="margin-bottom:16px;">
                            <span>模型回复</span>
                            <textarea class="input" rows="4" readonly><?php echo e($testResult['assistant_text'] !== '' ? $testResult['assistant_text'] : '未提取到 assistant 回复内容'); ?></textarea>
                        </div>
                        <div class="input-group">
                            <span>原始响应</span>
                            <textarea class="input" rows="8" readonly><?php echo e($testResult['response_body']); ?></textarea>
                        </div>
                    <?php endif; ?>
                </section>
                <script>document.getElementById('test-result').scrollIntoView({behavior:'smooth'});</script>
            <?php endif; ?>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
(function(){
    var catalog = <?php echo $catalogJson; ?>;
    var selModel = document.getElementById('sel-model');
    var txtProvider = document.getElementById('txt-provider');
    var grpEndpoint = document.getElementById('grp-endpoint');
    function onModelChange(){
        var key = selModel.value;
        var m = catalog[key] || null;
        txtProvider.value = m ? m.provider : '';
        if(m && m.requires_endpoint_id){
            grpEndpoint.style.display = '';
        } else {
            grpEndpoint.style.display = 'none';
        }
    }
    selModel.addEventListener('change', onModelChange);
    onModelChange();
})();
</script>
</body>
</html>
