import os
from datetime import datetime, timedelta
import json
from typing import List

# 列出文件夹中所有的日志文件（当前日志 + 轮转日志）
def list_logs(folder):
    if not os.path.isdir(folder):
        return []
    try:
        names = os.listdir(folder)
    except OSError:
        return []
    logs = []
    for file in names:
        # 当前日志：xxx.jsonl
        if file.endswith(".jsonl") and ".jsonl.reset." not in file:
            logs.append(os.path.join(folder, file))
        # 轮转日志：xxx.jsonl.reset.YYYY-MM-DDTHH-MM-SS.ZZZZ
        elif ".jsonl.reset." in file:
            logs.append(os.path.join(folder, file))
    return logs

# 获取日志保存的时间戳，返回该文件覆盖的日期 (当天, 前一天)
def get_log_save_time(file_path: str):
    """返回 (date1, date2)，表示该日志文件最多只包含 date1 和 date2 两天的数据。"""
    name = os.path.basename(file_path)
    # 当前日志：xxx.jsonl → 今天 + 昨天
    if name.endswith(".jsonl") and ".jsonl.reset." not in name:
        today = datetime.now().strftime("%Y-%m-%d")
        prev = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
        return today, prev
    # 轮转日志：xxx.jsonl.reset.YYYY-MM-DDTHH-MM-SS.703Z → 轮转日 + 轮转前一日
    if ".jsonl.reset." in name:
        part = name.split("reset.")[-1]
        save_date = part.split("T")[0]  # YYYY-MM-DD
        try:
            dt = datetime.strptime(save_date, "%Y-%m-%d")
            prev = (dt - timedelta(days=1)).strftime("%Y-%m-%d")
            return save_date, prev
        except ValueError:
            return None, None
    return None, None

def extract_user_questions(path: str) -> List[dict]:
    """
    从日志 jsonl 中提取用户提问及对应的回答。
    返回格式: [{"Q": "问题", "DATE": "Y-M-D H:M:S", "A": "回答"}, ...]
    只保留包含 message_id 的用户消息。
    """
    records = []
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                records.append(json.loads(line))
            except json.JSONDecodeError:
                continue

    results: List[dict] = []

    for i, record in enumerate(records):
        if record.get("type") != "message":
            continue
        message = record.get("message", {})
        if message.get("role") != "user":
            continue

        question = None
        date_str = None

        for item in (message.get("content") or []):
            if item.get("type") != "text":
                continue
            text = item.get("text", "")
            if '"message_id"' not in text:
                continue

            lines = [l.strip() for l in text.splitlines() if l.strip()]
            last_line = lines[-1] if lines else ""
            question = None

            # 格式一：末行形如 [Fri 2026-03-06 16:09 GMT+8] 算能有哪些产品
            if last_line.startswith("[") and "]" in last_line:
                time_part, question = last_line.split("]", 1)
                question = question.strip()
                ts = record.get("timestamp", "")
                try:
                    dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
                    dt_local = dt.astimezone()
                    date_str = dt_local.strftime("%Y-%m-%d %H:%M:%S")
                except Exception:
                    date_str = time_part.strip("[] ").strip()
            else:
                # 格式二：Conversation info + 元数据 JSON 块 + 空行 + 问题（无方括号时间戳）
                # 取最后一行作为问题，跳过纯 JSON/代码块行
                for candidate in reversed(lines):
                    if candidate.startswith("```") or candidate.startswith("{") or candidate.startswith("}"):
                        continue
                    if "message_id" in candidate and "sender" in candidate:
                        continue
                    question = candidate.strip()
                    break
                ts = record.get("timestamp", "")
                try:
                    dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
                    dt_local = dt.astimezone()
                    date_str = dt_local.strftime("%Y-%m-%d %H:%M:%S")
                except Exception:
                    date_str = ""
            if question:
                break

        if question is None:
            continue

        # 向后收集 assistant 的文本回答，直到遇到下一个 user 消息
        answer_parts = []
        for j in range(i + 1, len(records)):
            r = records[j]
            if r.get("type") != "message":
                continue
            msg = r.get("message", {})
            if msg.get("role") == "user":
                break
            if msg.get("role") == "assistant":
                for item in (msg.get("content") or []):
                    if item.get("type") == "text" and item.get("text", "").strip():
                        answer_parts.append(item["text"].strip())

        results.append({
            "Q": question,
            "DATE": date_str,
            "A": "\n".join(answer_parts),
        })

    return results


def get_daily_qa(date: str, log_folder: str="/home/node/.openclaw/agents/ai-cs-qa/sessions/") -> List[dict]:
    """
    按日期汇总当天的 QA 结果。仅根据 get_log_save_time 读取可能包含该日期的日志文件。

    参数:
        date: 查询日期，格式 'YYYY-MM-DD'
        log_folder: 日志文件所在目录

    返回:
        [{"Q": "问题", "DATE": "YYYY-MM-DD HH:MM:SS", "A": "回答"}, ...]
    """
    daily_results: List[dict] = []

    for log_path in list_logs(log_folder):
        d1, d2 = get_log_save_time(log_path)
        if d1 is None or date not in (d1, d2):
            continue

        try:
            qas = extract_user_questions(log_path)
        except FileNotFoundError:
            continue

        for item in qas:
            dt_str = (item.get("DATE") or "").strip()
            if dt_str.startswith(date):
                daily_results.append(item)

    return daily_results


# 默认 QA 会话日志目录（可被 skill/CLI 覆盖）
DEFAULT_LOG_FOLDER = "/home/node/.openclaw/agents/ai-cs-qa/sessions/"


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="查询指定日期的 QA 记录")
    parser.add_argument(
        "date",
        nargs="?",
        default=datetime.now().strftime("%Y-%m-%d"),
        help="查询日期，格式 YYYY-MM-DD，默认今天",
    )
    parser.add_argument(
        "--log-dir",
        "-d",
        default=DEFAULT_LOG_FOLDER,
        help="日志目录，默认 %(default)s",
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="以 JSON 数组输出",
    )
    args = parser.parse_args()

    daily_qa = get_daily_qa(args.date, args.log_dir)
    if args.json:
        print(json.dumps(daily_qa, ensure_ascii=False, indent=2))
    else:
        for qa in daily_qa:
            print(f"[{qa.get('DATE', '')}] Q: {qa.get('Q', '')}")
            print(f"  A: {qa.get('A', '')}")
            print()