#!/usr/bin/env python3
"""芬香妈妈看板服务 - 静态文件 + 数据分析API"""
import http.server
import json
import sqlite3
import os
import re
from urllib.parse import urlparse, unquote

DB_PATH = "/root/.openclaw/workspace-shortvideo/video-analytics/video_analytics.db"
STATIC_DIR = "/root/.openclaw/public-share"
PORT = 8088


def query_analytics():
    """查数据库，返回看板所需的完整数据结构"""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    # 查视频
    c.execute("SELECT * FROM videos ORDER BY id")
    videos = [dict(row) for row in c.fetchall()]

    # 查发布
    c.execute("SELECT * FROM postings ORDER BY video_id, id")
    postings = [dict(row) for row in c.fetchall()]

    # 查快照
    c.execute("SELECT * FROM snapshots ORDER BY posting_id, captured_at")
    snapshots = [dict(row) for row in c.fetchall()]

    conn.close()

    # 组装：video -> postings -> snapshots + 计算字段
    result = []
    for v in videos:
        vid = dict(v)
        vid["postings"] = []
        for p in postings:
            if p["video_id"] != v["id"]:
                continue
            posting = dict(p)
            posting["snapshots"] = []
            for s in snapshots:
                if s["posting_id"] != p["id"]:
                    continue
                posting["snapshots"].append(dict(s))

            # 计算 latest 和 gain
            if posting["snapshots"]:
                latest = posting["snapshots"][-1]
                posting["latest_likes"] = latest["likes"]
                posting["latest_views"] = latest["views"]
                posting["latest_comments"] = latest["comments"]
                posting["latest_shares"] = latest["shares"]
                posting["latest_status"] = latest["account_status"]
                posting["latest_update"] = latest["captured_at"]

                first = posting["snapshots"][0]
                posting["total_gain_views"] = latest["views"] - first["views"]
                posting["total_gain_likes"] = latest["likes"] - first["likes"]
                posting["total_gain_comments"] = latest["comments"] - first["comments"]
                posting["total_gain_shares"] = latest["shares"] - first["shares"]
            else:
                posting["latest_likes"] = 0
                posting["latest_views"] = 0
                posting["latest_comments"] = 0
                posting["latest_shares"] = 0
                posting["latest_status"] = "正常"
                posting["latest_update"] = p["created_at"]
                posting["total_gain_views"] = 0
                posting["total_gain_likes"] = 0
                posting["total_gain_comments"] = 0
                posting["total_gain_shares"] = 0

            vid["postings"].append(posting)
        result.append(vid)

    return result


class AnalyticsHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=STATIC_DIR, **kwargs)

    def do_GET(self):
        parsed = urlparse(self.path)
        path = unquote(parsed.path)

        if path == "/api/data":
            self._serve_api()
        else:
            super().do_GET()

    def _serve_api(self):
        try:
            data = query_analytics()
            body = json.dumps(data, ensure_ascii=False).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Access-Control-Allow-Origin", "*")
            self.send_header("Cache-Control", "no-cache")
            self.end_headers()
            self.wfile.write(body)
        except Exception as e:
            self.send_response(500)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"error": str(e)}).encode())

    def log_message(self, format, *args):
        # 保持简洁日志
        if "/api/data" in (args[0] if args else ""):
            print(f"[API] {args[0]}")
        else:
            super().log_message(format, *args)


if __name__ == "__main__":
    server = http.server.HTTPServer(("0.0.0.0", PORT), AnalyticsHandler)
    print(f"📊 芬香妈妈看板服务: http://0.0.0.0:{PORT}")
    server.serve_forever()
