"""Gate control — temporal gatekeeping for outreach.

When the gate is CLOSED: harvesting, enrichment, and drafting continue normally,
but no leads are selected for outreach (brief generation is blocked).
When the gate is OPEN: full pipeline operates normally.

Gate state is persisted in data/gate.json.
"""

import json
from datetime import datetime
from pathlib import Path
from typing import Optional


DEFAULT_GATE_PATH = "./data/gate.json"


def _get_gate_path() -> Path:
    """Get gate state file path."""
    import os
    path = os.environ.get("ABSEL_GATE_PATH", DEFAULT_GATE_PATH)
    return Path(path)


def load_gate() -> dict:
    """Load gate state. Returns default open state if file doesn't exist."""
    gate_path = _get_gate_path()

    if not gate_path.exists():
        return {
            "open": True,
            "closed_at": None,
            "closed_reason": None,
            "closed_by": None,
            "opened_at": None,
            "opened_reason": None,
        }

    try:
        with open(gate_path, 'r') as f:
            return json.loads(f.read())
    except (json.JSONDecodeError, IOError):
        return {
            "open": True,
            "closed_at": None,
            "closed_reason": None,
            "closed_by": None,
            "opened_at": None,
            "opened_reason": None,
        }


def save_gate(state: dict) -> None:
    """Save gate state atomically."""
    gate_path = _get_gate_path()
    gate_path.parent.mkdir(parents=True, exist_ok=True)

    with open(gate_path, 'w') as f:
        json.dump(state, f, indent=2)
        f.flush()


def close_gate(reason: str = "", operator: str = "") -> dict:
    """Close the gate — pause all outreach while allowing harvest/enrich/draft.

    Args:
        reason: Why the gate is being closed
        operator: Who closed the gate

    Returns:
        Updated gate state dict with status field
    """
    state = load_gate()

    if not state["open"]:
        state["status"] = "CLOSED"
        return state

    now = datetime.utcnow().isoformat() + "Z"

    state["open"] = False
    state["closed_at"] = now
    state["closed_reason"] = reason
    state["closed_by"] = operator
    state["opened_at"] = None
    state["opened_reason"] = None

    save_gate(state)
    state["status"] = "CLOSED"
    return state


def open_gate(reason: str = "") -> dict:
    """Open the gate — resume full pipeline operations.

    Args:
        reason: Why the gate is being opened

    Returns:
        Updated gate state dict with status field
    """
    state = load_gate()

    if state["open"]:
        state["status"] = "OPEN"
        return state

    now = datetime.utcnow().isoformat() + "Z"

    state["open"] = True
    state["opened_at"] = now
    state["opened_reason"] = reason

    save_gate(state)
    state["status"] = "OPEN"
    return state


def is_gate_open() -> bool:
    """Check if the gate is currently open."""
    return load_gate()["open"]


def gate_status() -> dict:
    """Get full gate status for display."""
    state = load_gate()
    status = "OPEN" if state["open"] else "CLOSED"
    state["status"] = status
    return state
