import requests
import json
from datetime import datetime

start_time = datetime.now().replace(hour=0, minute=0, second=0)
start_ns = int(start_time.timestamp()) * 1_000_000_000

url = 'http://localhost:3100/loki/api/v1/query_range'
params = {
    'query': '{service_name="exec"}',
    'start': start_ns,
    'limit': 500
}

response = requests.get(url, params=params)
data = response.json()

messages = []

if 'data' in data and 'result' in data['data']:
    for stream in data['data']['result']:
        for timestamp, log_entry in stream['values']:
            try:
                entry = json.loads(log_entry)
                message_str = entry.get('message', '')
                message = json.loads(message_str)
                
                msg_type = message.get('type', '')
                timestamp_str = message.get('timestamp', '')
                nested_message = message.get('message', {})
                content = nested_message.get('content', '')
                
                if msg_type == 'user':
                    if isinstance(content, str) and not content.startswith('Caveat:'):
                        messages.append({
                            'type': 'user',
                            'content': content,
                            'timestamp': timestamp_str
                        })
                elif msg_type == 'assistant':
                    if isinstance(content, list) and content:
                        text_content = []
                        for item in content:
                            if isinstance(item, dict) and item.get('type') == 'text':
                                text_content.append(item.get('text', ''))
                        if text_content:
                            messages.append({
                                'type': 'assistant',
                                'content': ' '.join(text_content),
                                'timestamp': timestamp_str
                            })
            except:
                pass

# 按时间排序
messages.sort(key=lambda x: x['timestamp'])

# 生成HTML
html = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>iFlow 对话记录 - {start_time.strftime('%Y-%m-%d')}</title>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }}
        .header {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px 10px 0 0;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        .header h1 {{
            font-size: 24px;
            margin-bottom: 10px;
        }}
        .header p {{
            font-size: 14px;
            opacity: 0.9;
        }}
        .stats {{
            display: flex;
            justify-content: space-around;
            background: white;
            padding: 15px;
            margin-top: 0;
            border-radius: 0 0 10px 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        .stat-item {{
            text-align: center;
        }}
        .stat-item .number {{
            font-size: 24px;
            font-weight: bold;
            color: #667eea;
        }}
        .stat-item .label {{
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }}
        .chat-container {{
            margin-top: 20px;
        }}
        .message {{
            display: flex;
            margin-bottom: 15px;
            align-items: flex-start;
        }}
        .message.user {{
            justify-content: flex-end;
        }}
        .message.assistant {{
            justify-content: flex-start;
        }}
        .avatar {{
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            color: white;
            flex-shrink: 0;
            margin: 0 10px;
        }}
        .message.user .avatar {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }}
        .message.assistant .avatar {{
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }}
        .bubble {{
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 12px;
            position: relative;
            word-wrap: break-word;
            line-height: 1.5;
        }}
        .message.user .bubble {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 2px 12px;
        }}
        .message.assistant .bubble {{
            background: white;
            color: #333;
            border-radius: 12px 12px 12px 2px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }}
        .time {{
            font-size: 11px;
            color: #999;
            margin-top: 5px;
            text-align: right;
        }}
        .message.assistant .time {{
            text-align: left;
        }}
        pre {{
            white-space: pre-wrap;
            word-wrap: break-word;
            margin: 0;
            font-family: inherit;
        }}
    </style>
</head>
<body>
    <div class="header">
        <h1>📅 iFlow 对话记录</h1>
        <p>{start_time.strftime('%Y年%m月%d日')}</p>
    </div>
    <div class="stats">
        <div class="stat-item">
            <div class="number">{len([m for m in messages if m['type'] == 'user'])}</div>
            <div class="label">用户消息</div>
        </div>
        <div class="stat-item">
            <div class="number">{len([m for m in messages if m['type'] == 'assistant'])}</div>
            <div class="label">AI回复</div>
        </div>
        <div class="stat-item">
            <div class="number">{len(messages)}</div>
            <div class="label">总计</div>
        </div>
    </div>
    <div class="chat-container">
"""

for msg in messages:
    if msg['type'] == 'user':
        html += f"""        <div class="message user">
            <div class="bubble">
                <pre>{msg['content']}</pre>
                <div class="time">{msg['timestamp'].split('T')[1][:8]}</div>
            </div>
            <div class="avatar">👤</div>
        </div>
"""
    else:
        html += f"""        <div class="message assistant">
            <div class="avatar">🤖</div>
            <div class="bubble">
                <pre>{msg['content'][:500]}</pre>
                <div class="time">{msg['timestamp'].split('T')[1][:8]}</div>
            </div>
        </div>
"""

html += """    </div>
</body>
</html>"""

# 保存HTML文件
output_path = '/tmp/iflow_chat.html'
with open(output_path, 'w', encoding='utf-8') as f:
    f.write(html)

print(f'✅ 已生成对话记录: {output_path}')
print(f'📊 共 {len(messages)} 条消息')
print(f'👤 用户: {len([m for m in messages if m["type"] == "user"])} 条')
print(f'🤖 AI: {len([m for m in messages if m["type"] == "assistant"])} 条')
