"""日志记录 Skill。"""

import sqlite3
from pathlib import Path

from butler.skills.base import SkillBase, SkillContext, SkillResult


class LogSkill(SkillBase):
    """记录和检索 Shell 交互日志。"""

    name = "log"
    description = "记录和检索 Shell 交互日志"
    triggers = ["/log", "/history"]

    def __init__(self, db_path: str = "data/logs.db"):
        self.db_path = Path(db_path)
        if self.db_path != ":memory:":
            self.db_path.parent.mkdir(parents=True, exist_ok=True)
        self._init_db()

    def _init_db(self) -> None:
        conn = sqlite3.connect(self.db_path)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS shell_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id TEXT NOT NULL,
                session_name TEXT NOT NULL,
                command TEXT NOT NULL,
                output TEXT,
                timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        """)
        conn.execute("CREATE INDEX IF NOT EXISTS idx_user ON shell_logs(user_id)")
        conn.execute("CREATE INDEX IF NOT EXISTS idx_timestamp ON shell_logs(timestamp)")
        conn.commit()
        conn.close()

    def log_command(self, user_id: str, session_name: str, command: str, output: str = "") -> None:
        conn = sqlite3.connect(self.db_path)
        conn.execute(
            "INSERT INTO shell_logs (user_id, session_name, command, output) VALUES (?, ?, ?, ?)",
            (user_id, session_name, command, output),
        )
        conn.commit()
        conn.close()

    async def execute(self, ctx: SkillContext) -> SkillResult:
        args = ctx.args

        if not args or args[0] == "recent":
            limit = int(args[1]) if len(args) > 1 else 10
            return self._query_recent(ctx.user_id, limit)

        elif args[0] == "search":
            keyword = " ".join(args[1:]) if len(args) > 1 else ""
            return self._search_commands(ctx.user_id, keyword)

        return SkillResult(success=False, output="用法: /log [recent N|search 关键词]")

    def _query_recent(self, user_id: str, limit: int) -> SkillResult:
        conn = sqlite3.connect(self.db_path)
        cursor = conn.execute(
            "SELECT command, timestamp FROM shell_logs WHERE user_id = ? ORDER BY timestamp DESC LIMIT ?",
            (user_id, limit),
        )
        rows = cursor.fetchall()
        conn.close()

        output = "\n".join(f"[{row[1]}] {row[0]}" for row in rows)
        return SkillResult(success=True, output=output or "无日志记录")

    def _search_commands(self, user_id: str, keyword: str) -> SkillResult:
        conn = sqlite3.connect(self.db_path)
        cursor = conn.execute(
            "SELECT command, timestamp FROM shell_logs WHERE user_id = ? AND command LIKE ? ORDER BY timestamp DESC LIMIT 20",
            (user_id, f"%{keyword}%"),
        )
        rows = cursor.fetchall()
        conn.close()

        output = "\n".join(f"[{row[1]}] {row[0]}" for row in rows)
        return SkillResult(success=True, output=output or "无匹配记录")
