import json
import logging
import time
from typing import Optional, Dict, Any

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class RouterDecisionLogger:
    """
    Logs routing decisions for audit trail purposes.  Logs include task details,
    routing decision (RWL or manual), override reason (if manual), agent ID, and timestamp.
    Writes logs in JSONL format.
    """

    def __init__(self, log_file_path: str = "router_decisions.jsonl"):
        """
        Initializes the RouterDecisionLogger with a specified log file path.

        Args:
            log_file_path (str): The path to the log file (default: "router_decisions.jsonl").
        """
        self.log_file_path = log_file_path
        logging.info(f"RouterDecisionLogger initialized.  Logging to: {self.log_file_path}")

    def log_decision(self, task_description: str, complexity_score: int, decision: str,
                     agent_id: str, override_reason: Optional[str] = None) -> None:
        """
        Logs a routing decision to the JSONL file.

        Args:
            task_description (str): Description of the task.
            complexity_score (int): Complexity score of the task.
            decision (str): Routing decision (RWL or manual).
            agent_id (str): ID of the agent making the decision.
            override_reason (Optional[str]): Reason for manual override, if applicable.
        """

        log_entry: Dict[str, Any] = {
            "timestamp": time.time(),
            "task_description": task_description,
            "complexity_score": complexity_score,
            "routing_decision": decision,
            "agent_id": agent_id
        }

        if override_reason:
            log_entry["override_reason"] = override_reason

        try:
            with open(self.log_file_path, "a") as f:
                json.dump(log_entry, f)
                f.write("\n")  # JSONL format requires each JSON object on a new line
            logging.info(f"Successfully logged decision: {log_entry}")
        except Exception as e:
            logging.error(f"Error writing to log file: {e}")


if __name__ == '__main__':
    # Example Usage
    logger = RouterDecisionLogger()

    # Log a RWL decision
    logger.log_decision(
        task_description="Analyze market trends",
        complexity_score=7,
        decision="RWL",
        agent_id="agent123"
    )

    # Log a manual decision with override reason
    logger.log_decision(
        task_description="Handle critical customer complaint",
        complexity_score=9,
        decision="manual",
        agent_id="agent456",
        override_reason="Customer requires immediate personal attention"
    )