"""Delete chat + feedback rows past the retention window (PII / data-minimization control).

Run daily (see deploy/purge-old-logs.timer). Window is RETENTION_DAYS (default 90) from .env.
Safe to run repeatedly; deletes only rows older than the window.

Run:  python3 scripts/purge_old_logs.py
"""
import os
import sys

from dotenv import load_dotenv

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import db  # noqa: E402

load_dotenv()
RETENTION_DAYS = int(os.getenv("RETENTION_DAYS", "90"))


def main() -> None:
    if not db.enabled():
        print("DB not configured (DB_HOST unset); nothing to purge.")
        return
    conn = db.connect()
    try:
        with conn.cursor() as cur:
            # Feedback first (it references a chat row by vMessageID).
            cur.execute("DELETE FROM tbl_SupportChatFeedback WHERE dCreated < (NOW() - INTERVAL %s DAY)",
                        (RETENTION_DAYS,))
            fb = cur.rowcount
            cur.execute("DELETE FROM tbl_SupportChatLog WHERE dCreated < (NOW() - INTERVAL %s DAY)",
                        (RETENTION_DAYS,))
            chats = cur.rowcount
        conn.commit()
        print(f"Purged {chats} chat rows and {fb} feedback rows older than {RETENTION_DAYS} days.")
    finally:
        conn.close()


if __name__ == "__main__":
    main()
