"""Simple Admin UI for Normbase"""
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from normbase.config import settings

app = FastAPI()

admin_html = """
<!DOCTYPE html>
<html>
<head>
    <title>AIF Normbase Admin</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        h1 { color: #333; margin-bottom: 20px; }
        .nav { background: white; padding: 15px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .nav a { margin-right: 20px; text-decoration: none; color: #007bff; font-weight: 500; }
        .nav a:hover { text-decoration: underline; }
        .card { background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        button { background: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 14px; }
        button:hover { background: #0056b3; }
        button.danger { background: #dc3545; }
        button.danger:hover { background: #c82333; }
        button.success { background: #28a745; }
        button.success:hover { background: #218838; }
        input, select, textarea { padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; width: 100%; margin-bottom: 10px; }
        textarea { min-height: 100px; font-family: monospace; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-weight: 500; color: #333; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
        th { background: #f8f9fa; font-weight: 600; }
        .badge { display: inline-block; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: 500; }
        .badge-active { background: #d4edda; color: #155724; }
        .badge-draft { background: #fff3cd; color: #856404; }
        .badge-deprecated { background: #f8d7da; color: #721c24; }
        .actions { display: flex; gap: 10px; }
        .loading { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.9); display: flex; justify-content: center; align-items: center; z-index: 1000; }
        .hidden { display: none; }
    </style>
</head>
<body>
    <div class="container">
        <h1>AIF Normbase Admin</h1>
        <div class="nav">
            <a href="#" onclick="showPage('list')">规范列表</a>
            <a href="#" onclick="showPage('create')">创建规范</a>
            <a href="#" onclick="loadNorms()">🔄 刷新</a>
        </div>
        
        <div id="list-page">
            <div class="card">
                <h2>规范列表</h2>
                <p>共 <span id="norm-count">0</span> 条规范</p>
            </div>
            <div class="card">
                <table id="norms-table">
                    <thead>
                        <tr><th>ID</th><th>名称</th><th>类型</th><th>权威层级</th><th>领域</th><th>状态</th><th>操作</th></tr>
                    </thead>
                    <tbody id="norms-tbody"></tbody>
                </table>
            </div>
        </div>
        
        <div id="detail-page" class="hidden"></div>
        
        <div id="form-page" class="hidden">
            <div class="card">
                <h2>创建规范</h2>
                <form id="norm-form">
                    <div class="form-group"><label>规范名称 *</label><input type="text" name="name" required></div>
                    <div class="form-group">
                        <label>类型 *</label>
                        <select name="norm_type" required>
                            <option value="obligation">义务 (obligation)</option>
                            <option value="prohibition">禁止 (prohibition)</option>
                            <option value="permission">许可 (permission)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>权威层级</label>
                        <select name="authority_level">
                            <option value="">请选择</option>
                            <option value="legal">法律 (legal)</option>
                            <option value="industry">行业 (industry)</option>
                            <option value="organizational">组织 (organizational)</option>
                        </select>
                    </div>
                    <div class="form-group"><label>领域</label><input type="text" name="domain"></div>
                    <div class="form-group"><label>适用角色 (JSON 数组)</label><input type="text" name="scope_roles" value='["*"]'></div>
                    <div class="form-group"><label>条件 (JSON)</label><textarea name="condition">{}</textarea></div>
                    <div class="form-group"><label>行动 (JSON)</label><textarea name="action">{}</textarea></div>
                    <div class="form-group"><label>后果 (JSON)</label><textarea name="consequence">{}</textarea></div>
                    <div class="form-group"><label>格式化提示</label><textarea name="formatted_prompt"></textarea></div>
                    <div class="form-group"><label>来源</label><input type="text" name="source"></div>
                    <div class="form-group">
                        <label>状态</label>
                        <select name="status">
                            <option value="draft">草稿</option>
                            <option value="active">激活</option>
                            <option value="deprecated">废弃</option>
                        </select>
                    </div>
                    <button type="submit" class="success">保存</button>
                    <button type="button" onclick="showPage('list')" class="danger">取消</button>
                </form>
            </div>
        </div>
        
        <div id="loading" class="loading hidden">加载中...</div>
    </div>
    
    <script>
        const API_BASE = '__API_BASE__';
        
        function showPage(page) {
            document.getElementById('list-page').classList.toggle('hidden', page !== 'list');
            document.getElementById('detail-page').classList.toggle('hidden', page !== 'detail');
            document.getElementById('form-page').classList.toggle('hidden', page !== 'create');
            if (page === 'list') loadNorms();
        }
        
        function showLoading() { document.getElementById('loading').classList.remove('hidden'); }
        function hideLoading() { document.getElementById('loading').classList.add('hidden'); }
        
        async function loadNorms() {
            showLoading();
            try {
                const res = await fetch(API_BASE + '/norms?page_size=100');
                const data = await res.json();
                document.getElementById('norm-count').textContent = data.total;
                const tbody = document.getElementById('norms-tbody');
                tbody.innerHTML = '';
                for (const norm of data.items) {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${norm.id.substring(0, 8)}...</td>
                        <td>${norm.name}</td>
                        <td>${norm.norm_type}</td>
                        <td>${norm.authority_level || '-'}</td>
                        <td>${norm.domain || '-'}</td>
                        <td><span class="badge badge-${norm.status}">${norm.status}</span></td>
                        <td class="actions">
                            <button onclick="viewNorm('${norm.id}')">查看</button>
                            <button class="danger" onclick="deleteNorm('${norm.id}')">删除</button>
                        </td>
                    `;
                    tbody.appendChild(tr);
                }
            } catch (e) { alert('加载失败: ' + e.message); }
            hideLoading();
        }
        
        document.getElementById('norm-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            showLoading();
            const form = e.target;
            const data = {
                name: form.name.value,
                norm_type: form.norm_type.value,
                authority_level: form.authority_level.value || null,
                domain: form.domain.value || null,
                scope_roles: JSON.parse(form.scope_roles.value || '[]'),
                condition: JSON.parse(form.condition.value || '{}'),
                action: JSON.parse(form.action.value || '{}'),
                consequence: JSON.parse(form.consequence.value || '{}'),
                formatted_prompt: form.formatted_prompt.value || null,
                source: form.source.value || null,
                status: form.status.value
            };
            try {
                const res = await fetch(API_BASE + '/norms', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) });
                if (res.ok) { alert('创建成功!'); form.reset(); showPage('list'); }
                else { const err = await res.json(); alert('创建失败: ' + (err.detail || JSON.stringify(err))); }
            } catch (e) { alert('错误: ' + e.message); }
            hideLoading();
        });
        
        async function deleteNorm(id) {
            if (!confirm('确定删除?')) return;
            showLoading();
            try { await fetch(API_BASE + '/norms/' + id, {method: 'DELETE'}); loadNorms(); }
            catch (e) { alert('删除失败: ' + e.message); }
            hideLoading();
        }
        
        async function viewNorm(id) {
            showLoading();
            try {
                const res = await fetch(API_BASE + '/norms/' + id);
                const norm = await res.json();
                const detailHtml = `
                    <div class="card">
                        <h2>规范详情</h2>
                        <table>
                            <tr><th>ID</th><td>${norm.id}</td></tr>
                            <tr><th>名称</th><td>${norm.name}</td></tr>
                            <tr><th>类型</th><td>${norm.norm_type}</td></tr>
                            <tr><th>权威层级</th><td>${norm.authority_level || '-'}</td></tr>
                            <tr><th>领域</th><td>${norm.domain || '-'}</td></tr>
                            <tr><th>信息场ID</th><td>${norm.field_id || '-'}</td></tr>
                            <tr><th>状态</th><td>${norm.status}</td></tr>
                            <tr><th>版本</th><td>${norm.version}</td></tr>
                            <tr><th>来源</th><td>${norm.source || '-'}</td></tr>
                            <tr><th>来源详情</th><td><pre>${norm.source_details ? JSON.stringify(norm.source_details, null, 2) : '-'}</pre></td></tr>
                            <tr><th>适用角色</th><td>${JSON.stringify(norm.scope_roles)}</td></tr>
                            <tr><th>适用上下文</th><td>${JSON.stringify(norm.scope_contexts)}</td></tr>
                            <tr><th>条件</th><td><pre>${JSON.stringify(norm.condition, null, 2)}</pre></td></tr>
                            <tr><th>行动</th><td><pre>${JSON.stringify(norm.action, null, 2)}</pre></td></tr>
                            <tr><th>后果</th><td><pre>${JSON.stringify(norm.consequence, null, 2)}</pre></td></tr>
                            <tr><th>格式化提示</th><td><pre style="white-space: pre-wrap;">${(norm.formatted_prompt || '-').replace(/\\\\n/g, String.fromCharCode(10))}</pre></td></tr>
                            <tr><th>关联案例</th><td>${JSON.stringify(norm.case_refs)}</td></tr>
                            <tr><th>创建者</th><td>${norm.created_by || '-'}</td></tr>
                            <tr><th>创建时间</th><td>${norm.created_at}</td></tr>
                            <tr><th>更新时间</th><td>${norm.updated_at}</td></tr>
                        </table>
                        <br><button onclick="showPage('list')">返回列表</button>
                    </div>
                `;
                document.getElementById('detail-page').innerHTML = detailHtml;
                document.getElementById('list-page').classList.add('hidden');
                document.getElementById('detail-page').classList.remove('hidden');
                document.getElementById('form-page').classList.add('hidden');
            } catch (e) { alert('加载失败: ' + e.message); }
            hideLoading();
        }
        
        loadNorms();
    </script>
</body>
</html>
"""

@app.get("/", response_class=HTMLResponse)
async def admin_ui(request: Request):
    del request
    return HTMLResponse(
        content=admin_html.replace("__API_BASE__", f"{settings.normbase_base_url}/api/v1")
    )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "normbase.admin:app",
        host=settings.api_host,
        port=settings.ui_port,
        reload=settings.api_debug,
    )
