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73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { getRecentLogs, clearLogFile } from './utils/logger.js';
import { info as log, error as logError } from './utils/logger.js';
import config from './config.js';

const app = new Hono();

// 静态文件服务 - 提供 screenshots 目录
app.use('/screenshots/*', serveStatic({ root: './' }));

// 静态 HTML 页面
const indexHTML = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CloudStudio Runner - 日志查看器</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        .header h1 {
            margin: 0;
            font-size: 2em;
        }
        .header p {
            margin: 10px 0 0 0;
            opacity: 0.9;
        }
        .controls {
            padding: 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }
        .controls label {
            font-weight: bold;
        }
        .controls select, .controls button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .controls button {
            background: #667eea;
            color: white;
            border: none;
            cursor: pointer;
            transition: background 0.3s;
        }
        .controls button:hover {
            background: #5a6fd8;
        }
        .log-container {
            padding: 20px;
            max-height: 600px;
            overflow-y: auto;
        }
        .log-entry {
            margin-bottom: 8px;
            padding: 8px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.4;
            border-left: 3px solid #ddd;
        }
        .log-entry.info {
            background-color: #f8f9fa;
            border-left-color: #28a745;
        }
        .log-entry.error {
            background-color: #fff5f5;
            border-left-color: #dc3545;
            color: #721c24;
        }
        .log-entry.warn {
            background-color: #fffbf0;
            border-left-color: #ffc107;
            color: #856404;
        }
        .timestamp {
            color: #6c757d;
            font-weight: bold;
        }
        .level {
            font-weight: bold;
            margin: 0 8px;
        }
        .level.info { color: #28a745; }
        .level.error { color: #dc3545; }
        .level.warn { color: #ffc107; }
        .message {
            word-break: break-word;
        }
        .status {
            padding: 10px 20px;
            background: #e9ecef;
            border-top: 1px solid #ddd;
            font-size: 14px;
            color: #6c757d;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }
        .empty {
            text-align: center;
            padding: 40px;
            color: #6c757d;
            font-style: italic;
        }
        .screenshot-section {
            padding: 20px;
            border-bottom: 1px solid #eee;
            text-align: center;
        }
        .screenshot-section h2 {
            margin: 0 0 15px 0;
            color: #333;
            font-size: 1.2em;
        }
        .screenshot-section img {
            max-width: 100%;
            height: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 CloudStudio Runner</h1>
            <p>实时日志查看器 - 监控自动化任务执行状态</p>
        </div>

        <div class="controls">
            <label for="lines">显示行数:</label>
            <select id="lines">
                <option value="50">50 行</option>
                <option value="100" selected>100 行</option>
                <option value="200">200 行</option>
                <option value="500">500 行</option>
                <option value="1000">1000 行</option>
            </select>

            <button onclick="refreshLogs()">🔄 刷新日志</button>
            <button onclick="toggleAutoRefresh()">⏱️ 自动刷新</button>
            <button onclick="clearLogs()">🗑️ 清空显示</button>
        </div>

        <div class="log-container" id="logContainer">
            <div class="loading">正在加载日志...</div>
        </div>

        <div class="status" id="status">
            准备就绪
        </div>
        <div class="screenshot-section">
            <h2>📸 最新截图</h2>
            <img src="/screenshots/scheduler.png" alt="Scheduler Screenshot" onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
            <div style="display: none; color: #6c757d; font-style: italic;">截图文件不存在或无法加载</div>
        </div>
    </div>

    <script>
        let autoRefreshInterval = null;
        let isAutoRefresh = false;

        async function fetchLogs() {
            try {
                const lines = document.getElementById('lines').value;
                const response = await fetch(\`/api/logs?lines=\${lines}\`);
                const data = await response.json();

                if (data.success) {
                    displayLogs(data.logs);
                    updateStatus(\`已加载 \${data.logs.length} 条日志 - \${new Date().toLocaleString()}\`);
                } else {
                    updateStatus('获取日志失败: ' + data.error);
                }
            } catch (error) {
                updateStatus('网络错误: ' + error.message);
            }
        }

        function displayLogs(logs) {
            const container = document.getElementById('logContainer');

            if (logs.length === 0) {
                container.innerHTML = '<div class="empty">暂无日志数据</div>';
                return;
            }

            const logHTML = logs.map(log => {
                const match = log.match(/\\[(.*?)\\]\\s*\\[(.*?)\\]\\s*(.*)/);
                if (match) {
                    const [, timestamp, level, message] = match;
                    const levelClass = level.toLowerCase();
                    return \`
                        <div class="log-entry \${levelClass}">
                            <span class="timestamp">\${timestamp}</span>
                            <span class="level \${levelClass}">[\${level}]</span>
                            <span class="message">\${message}</span>
                        </div>
                    \`;
                } else {
                    return \`
                        <div class="log-entry">
                            <span class="message">\${log}</span>
                        </div>
                    \`;
                }
            }).join('');

            container.innerHTML = logHTML;
            container.scrollTop = container.scrollHeight;
        }

        function updateStatus(message) {
            document.getElementById('status').textContent = message;
        }

        function refreshLogs() {
            fetchLogs();
        }

        function toggleAutoRefresh() {
            const button = event.target;

            if (isAutoRefresh) {
                clearInterval(autoRefreshInterval);
                autoRefreshInterval = null;
                isAutoRefresh = false;
                button.textContent = '⏱️ 自动刷新';
                updateStatus('自动刷新已停止');
            } else {
                autoRefreshInterval = setInterval(fetchLogs, 5000);
                isAutoRefresh = true;
                button.textContent = '⏹️ 停止刷新';
                updateStatus('自动刷新已启动 (每5秒)');
            }
        }

        async function clearLogs() {
            try {
                updateStatus('正在清空日志...');

                const response = await fetch('/api/clear-logs', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                const data = await response.json();

                if (data.success) {
                    document.getElementById('logContainer').innerHTML = '<div class="empty">日志已清空</div>';
                    updateStatus('日志文件已清空 - ' + new Date().toLocaleString());
                } else {
                    updateStatus('清空日志失败: ' + data.error);
                }
            } catch (error) {
                updateStatus('清空日志时发生网络错误: ' + error.message);
            }
        }

        // 页面加载时获取日志
        document.addEventListener('DOMContentLoaded', fetchLogs);
    </script>
</body>
</html>
`;

// 路由定义
app.get('/', (c) => {
    return c.html(indexHTML);
});

// API 路由 - 获取日志
app.get('/api/logs', (c) => {
    try {
        const lines = parseInt(c.req.query('lines') || '100');
        const logs = getRecentLogs(lines);

        return c.json({
            success: true,
            logs: logs,
            count: logs.length,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        logError('获取日志API错误:', error);
        return c.json({
            success: false,
            error: error.message
        }, 500);
    }
});

// API 路由 - 清空日志
app.post('/api/clear-logs', (c) => {
    try {
        const success = clearLogFile();

        if (success) {
            log('日志文件已通过Web界面清空');
            return c.json({
                success: true,
                message: '日志文件已清空',
                timestamp: new Date().toISOString()
            });
        } else {
            return c.json({
                success: false,
                error: '清空日志文件失败'
            }, 500);
        }
    } catch (error) {
        logError('清空日志API错误:', error);
        return c.json({
            success: false,
            error: error.message
        }, 500);
    }
});

// API 路由 - 系统状态
app.get('/api/status', (c) => {
    return c.json({
        success: true,
        status: 'running',
        uptime: process.uptime(),
        memory: process.memoryUsage(),
        timestamp: new Date().toISOString(),
        config: {
            webideUrl: config.webideUrl,
            schedulerInterval: config.schedulerInterval,
            headless: config.browserOptions.headless
        }
    });
});

// 健康检查
app.get('/health', (c) => {
    return c.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 启动服务器
const port = process.env.PORT || 7860;

async function startServer() {
    try {
        log(`启动 Web 服务器,端口: ${port}`);
        log(`访问地址: http://localhost:${port}`);

        serve({
            fetch: app.fetch,
            port: port,
        });

        log('Web 服务器启动成功');
    } catch (error) {
        logError('启动 Web 服务器失败:', error);
        process.exit(1);
    }
}

// 如果直接运行此文件,启动服务器
import { fileURLToPath } from 'url';
import path from 'path';

const __filename = fileURLToPath(import.meta.url);
const scriptPath = path.resolve(process.argv[1]);

if (path.resolve(__filename) === scriptPath) {
    startServer();
}

export { app, startServer };