"""obol override - consume a one-time override code from enforce mode.

When gate.py blocks a command in enforce mode, it generates a 6-char code.
Running `obol override <CODE>` within 60 seconds creates an override file
that gate.py will consume on the next invocation to allow the blocked command.

    obol override A1B2C3    Allow the blocked command one time
"""
import json
import os
import sys
import time

OVERRIDE_PENDING_PATH = os.path.expanduser("~/.obol/.override_pending")
OVERRIDE_ACTIVE_PATH = os.path.expanduser("~/.obol/.override_active")


def cmd_override(args):
    code = getattr(args, "code", None)
    if not code:
        print("Usage: obol override <CODE>")
        print("The 6-character code is shown when enforce mode blocks a command.")
        return

    code = code.strip().upper()

    # Validate pending override
    if not os.path.exists(OVERRIDE_PENDING_PATH):
        print("No pending override found.")
        print("Override codes are generated when enforce mode blocks a command.")
        return

    try:
        with open(OVERRIDE_PENDING_PATH) as f:
            pending = json.load(f)
    except Exception:
        print("Error reading pending override.")
        return

    if not isinstance(pending, dict):
        print("Invalid pending override data.")
        return

    # Check code
    expected_code = pending.get("code", "")
    if code != expected_code:
        print("Invalid override code.")
        return

    # Check expiry
    expires = pending.get("expires_at", 0)
    if time.time() > expires:
        print("Override code has expired (60s TTL).")
        print("Re-run the blocked command to get a fresh code.")
        # Clean up expired pending
        try:
            os.unlink(OVERRIDE_PENDING_PATH)
        except Exception:
            pass
        return

    # Create active override (consumed by gate.py)
    active = {
        "tool_name": pending.get("tool_name", ""),
        "target_hash": pending.get("target_hash", ""),
        "flags": pending.get("flags", []),
        "created_at": time.time(),
        "expires_at": time.time() + 60,  # 60s to re-run the command
    }

    try:
        obol_dir = os.path.expanduser("~/.obol")
        os.makedirs(obol_dir, exist_ok=True)
        tmp = OVERRIDE_ACTIVE_PATH + ".tmp"
        fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, "w") as f:
            json.dump(active, f)
        os.replace(tmp, OVERRIDE_ACTIVE_PATH)
    except Exception as e:
        print(f"Error creating override: {e}")
        return

    # Clean up pending
    try:
        os.unlink(OVERRIDE_PENDING_PATH)
    except Exception:
        pass

    tool = pending.get("tool_name", "?")
    flags = pending.get("flags", [])
    print(f"Override activated for {tool}.")
    if flags:
        print(f"Suppressed flags: {', '.join(flags[:5])}")
    print("Re-run the blocked command within 60 seconds.")
    print("\nNote: this does NOT reset the critical count (lockdown threshold still applies).")


def setup_parser(subparsers):
    parser = subparsers.add_parser("override",
                                   help="One-time override for enforce mode blocks")
    parser.add_argument("code", nargs="?", help="6-character override code")
    parser.set_defaults(func=cmd_override)
