#!/usr/bin/env python3
"""Clear middleware cache for a terminal session.

Used by /clear-cache command and /handoff skill to purge cached tool results.

Usage:
    python hooks/clear_cache.py                    # Clear current terminal's cache
    python hooks/clear_cache.py --terminal-id ID   # Clear specific terminal's cache
    python hooks/clear_cache.py --all              # Clear ALL cache entries
"""

import argparse
import json
import os
import sys
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(description="Clear middleware cache")
    parser.add_argument("--terminal-id", help="Specific terminal ID to clear")
    parser.add_argument("--all", action="store_true", help="Clear all cache entries")
    args = parser.parse_args()

    project_path = os.environ.get("CLAUDE_PROJECT_DIR", os.getcwd())
    db_path = Path(project_path) / ".omni-cortex" / "cortex.db"

    if not db_path.exists():
        print(json.dumps({"cleared": 0, "message": "No database found"}))
        return

    try:
        # Import from sibling modules
        sys.path.insert(0, str(Path(__file__).parent))
        from middleware_cache import clear_session_cache, cleanup_expired_cache

        if args.all:
            # Clear ALL cache entries
            import sqlite3
            conn = sqlite3.connect(str(db_path))
            conn.execute("PRAGMA busy_timeout = 5000")
            cursor = conn.cursor()
            cursor.execute("DELETE FROM middleware_cache")
            conn.commit()
            removed = cursor.rowcount
            conn.close()
            print(json.dumps({"cleared": removed, "message": f"All cache entries cleared ({removed} removed)"}))
        else:
            # Determine terminal session ID
            terminal_session_id = None

            if args.terminal_id:
                # Load session file for specified terminal
                from session_utils import load_session_file
                session_data = load_session_file(args.terminal_id)
                if session_data:
                    terminal_session_id = session_data.get("session_id")
            else:
                # Auto-detect current terminal
                from session_utils import get_terminal_id, load_session_file
                terminal_id = get_terminal_id()
                session_data = load_session_file(terminal_id)
                if session_data:
                    terminal_session_id = session_data.get("session_id")

            if not terminal_session_id:
                print(json.dumps({"cleared": 0, "message": "No active session found for this terminal"}))
                return

            removed = clear_session_cache(db_path, terminal_session_id)

            # Also clean up expired entries while we're at it
            expired = cleanup_expired_cache(db_path)

            print(json.dumps({
                "cleared": removed,
                "expired_cleaned": expired,
                "message": f"Cache cleared. {removed} entries removed for this terminal session."
                           + (f" Also cleaned {expired} expired entries." if expired > 0 else ""),
            }))

    except Exception as e:
        print(json.dumps({"cleared": 0, "error": str(e)}))


if __name__ == "__main__":
    main()
