# ============================================================
# core/audit.py
# Audit trail — ghi lại mọi thao tác quan trọng trên DB
# ============================================================

import json
import sqlite3
from datetime import datetime
from typing import Optional
from core.db_init import get_conn


def log_action(conn: sqlite3.Connection, table: str, record_id: int,
               action: str, old_data: Optional[dict] = None,
               new_data: Optional[dict] = None, user: str = "system") -> None:
    """Ghi 1 dòng vào audit_log."""
    conn.execute("""
        INSERT OR IGNORE INTO audit_log
            (table_name, record_id, action, old_data, new_data, performed_by, performed_at)
        VALUES (?, ?, ?, ?, ?, ?, datetime('now','localtime'))
    """, (
        table, record_id, action,
        json.dumps(old_data, ensure_ascii=False) if old_data else None,
        json.dumps(new_data, ensure_ascii=False) if new_data else None,
        user,
    ))


def get_audit_history(db_path: str, table: str = None,
                      record_id: int = None, limit: int = 50) -> list:
    """Lấy lịch sử thay đổi từ audit_log."""
    conn = get_conn(db_path)
    c = conn.cursor()

    where_clauses = []
    params = []
    if table:
        where_clauses.append("table_name = ?")
        params.append(table)
    if record_id:
        where_clauses.append("record_id = ?")
        params.append(record_id)

    where_sql = ("WHERE " + " AND ".join(where_clauses)) if where_clauses else ""
    params.append(limit)

    rows = c.execute(f"""
        SELECT id, table_name, record_id, action, old_data, new_data,
               performed_by, performed_at
        FROM audit_log
        {where_sql}
        ORDER BY id DESC
        LIMIT ?
    """, params).fetchall()

    cols = [d[0] for d in c.description]
    conn.close()
    result = []
    for r in rows:
        row = dict(zip(cols, r))
        if row.get("old_data"):
            row["old_data"] = json.loads(row["old_data"])
        if row.get("new_data"):
            row["new_data"] = json.loads(row["new_data"])
        result.append(row)
    return result


def print_audit_history(db_path: str, table: str = None,
                        record_id: int = None) -> None:
    """In audit history ra terminal."""
    rows = get_audit_history(db_path, table, record_id)
    if not rows:
        print("(Không có lịch sử thay đổi)")
        return
    print(f"\n{'─'*70}")
    print(f"  AUDIT LOG{f' — {table}#{record_id}' if record_id else ''}")
    print(f"{'─'*70}")
    for r in rows:
        print(f"  [{r['performed_at']}] {r['action'].upper():8} {r['table_name']}#{r['record_id']} by {r['performed_by']}")
    print()
