import asyncio
import re
import hashlib
from datetime import datetime
from typing import Dict, Any
from aiva.db_connector import memory  # Assuming this exists as before

# --- Utility Functions ---

def calculate_score(checks: Dict[str, bool]) -> float:
    """Calculates an overall score based on boolean checks."""
    return sum(checks.values()) / len(checks) if checks else 1.0

def log_decision(gate_name: str, worker_id: str, passed: bool, reason: str, memory: Any) -> None:
    """Logs gate decisions with reasoning to audit trail."""
    try:
        memory.log_audit(f"{gate_name}_validation", worker_id, {"passed": passed, "reason": reason, "timestamp": datetime.utcnow().isoformat()})
    except Exception as e:
        print(f"[WARNING] Audit logging failed for {gate_name}: {e}")

# --- Gate Implementations ---

class GateAlpha:
    """Gate Alpha: Input Validity"""
    def __init__(self, memory: Any):
        self.memory = memory

    async def validate(self, input_data: str, worker_id: str, metadata: Dict[str, Any]) -> bool:
        """Validates the quality of input source data."""
        checks = {}
        checks["has_content"] = bool(input_data)
        checks["reasonable_length"] = 10 < len(input_data) < 10000  #Arbitrary limits, adjust as needed
        checks["format_valid"] = isinstance(input_data, str)

        passed = calculate_score(checks) >= 0.8

        reason = f"Input validity check: Content={checks['has_content']}, Length={checks['reasonable_length']}, Format={checks['format_valid']}"
        log_decision("gate_alpha", worker_id, passed, reason, self.memory)
        return passed

class GateBeta:
    """Gate Beta: Output Quality"""
    def __init__(self, memory: Any):
        self.memory = memory

    async def validate(self, output_data: str, expected_format: str, worker_id: str, metadata: Dict[str, Any]) -> bool:
        """Checks the accuracy and completeness of the output."""
        checks = {}
        checks["has_content"] = bool(output_data)
        checks["format_matches"] = expected_format in output_data  #Basic format validation
        checks["length_reasonable"] = 5 < len(output_data) < 5000  #Adjust as needed

        passed = calculate_score(checks) >= 0.8
        reason = f"Output quality check: Content={checks['has_content']}, Format={checks['format_matches']}, Length={checks['length_reasonable']}"
        log_decision("gate_beta", worker_id, passed, reason, self.memory)
        return passed

class GateGamma:
    """Gate Gamma: Insight Purity"""
    def __init__(self, memory: Any):
        self.memory = memory

    async def validate(self, output_data: str, task_description: str, worker_id: str, metadata: Dict[str, Any]) -> bool:
        """Detects hallucinations in the output by comparing to the task description."""
        checks = {}
        # Simple hallucination detection (can be improved with NLP techniques)
        checks["contains_task_keywords"] = all(keyword in output_data.lower() for keyword in task_description.lower().split())
        checks["reasonable_length"] = len(output_data) < 2000 # Arbitrary limit
        passed = calculate_score(checks) >= 0.7

        reason = f"Hallucination check: Keywords={checks['contains_task_keywords']}, Length={checks['reasonable_length']}"
        log_decision("gate_gamma", worker_id, passed, reason, self.memory)
        return passed

class GateDelta:
    """Gate Delta: Memory Integration"""
    def __init__(self, memory: Any):
        self.memory = memory

    async def validate(self, data_to_store: Dict[str, Any], worker_id: str, metadata: Dict[str, Any]) -> bool:
        """Validates data storage operations."""
        checks = {}
        try:
            self.memory.store_data(worker_id, data_to_store)  #Simulated storage
            checks["storage_successful"] = True
        except Exception as e:
            checks["storage_successful"] = False
            print(f"[ERROR] Memory storage failed: {e}")

        checks["data_present"] = self.memory.retrieve_data(worker_id) is not None

        passed = calculate_score(checks) >= 0.9
        reason = f"Memory integration check: Storage={checks['storage_successful']}, DataPresent={checks['data_present']}"
        log_decision("gate_delta", worker_id, passed, reason, self.memory)
        return passed

class GateEpsilon:
    """Gate Epsilon: Strategy Alignment"""
    def __init__(self, memory: Any):
        self.memory = memory

    async def validate(self, output_data: str, revenue_strategy: str, worker_id: str, metadata: Dict[str, Any]) -> bool:
        """Ensures that the output aligns with the defined revenue strategy."""
        checks = {}
        checks["strategy_keywords_present"] = all(keyword in output_data.lower() for keyword in revenue_strategy.lower().split())
        checks["no_conflicts_with_strategy"] = "avoid" not in output_data.lower() # simple conflict check

        passed = calculate_score(checks) >= 0.7
        reason = f"Strategy alignment check: Keywords={checks['strategy_keywords_present']}, Conflicts={not checks['no_conflicts_with_strategy']}"
        log_decision("gate_epsilon", worker_id, passed, reason, self.memory)
        return passed

class GateZeta:
    """Gate Zeta: Budget Compliance"""
    def __init__(self, memory: Any):
        self.memory = memory

    async def validate(self, resource_usage: float, budget_limit: float, worker_id: str, metadata: Dict[str, Any]) -> bool:
        """Monitors resource usage and ensures compliance with budget limits."""
        checks = {}
        checks["within_budget"] = resource_usage <= budget_limit
        checks["resource_usage_reasonable"] = resource_usage > 0 # Avoid zero usage
        passed = calculate_score(checks) >= 0.8

        reason = f"Budget compliance check: WithinBudget={checks['within_budget']}, ReasonableUsage={checks['resource_usage_reasonable']}"
        log_decision("gate_zeta", worker_id, passed, reason, self.memory)
        return passed

# --- Orchestrator ---

class SixGateValidator:
    def __init__(self):
        self.memory = memory
        self.gate_alpha = GateAlpha(memory)
        self.gate_beta = GateBeta(memory)
        self.gate_gamma = GateGamma(memory)
        self.gate_delta = GateDelta(memory)
        self.gate_epsilon = GateEpsilon(memory)
        self.gate_zeta = GateZeta(memory)

    async def validate_worker_output(self, input_data: str, output_data: str, task_description: str, worker_id: str, metadata: Dict[str, Any], expected_format: str, revenue_strategy: str, resource_usage: float, budget_limit: float, data_to_store: Dict[str, Any]):
        """Runs the 6-gate validation suite."""

        # Gate Alpha
        if not await self.gate_alpha.validate(input_data, worker_id, metadata):
            return self._create_report(worker_id, False, "Gate Alpha failed")

        # Gate Beta
        if not await self.gate_beta.validate(output_data, expected_format, worker_id, metadata):
            return self._create_report(worker_id, False, "Gate Beta failed")

        # Gate Gamma
        if not await self.gate_gamma.validate(output_data, task_description, worker_id, metadata):
            return self._create_report(worker_id, False, "Gate Gamma failed")

        # Gate Delta
        if not await self.gate_delta.validate(data_to_store, worker_id, metadata):
            return self._create_report(worker_id, False, "Gate Delta failed")

        # Gate Epsilon
        if not await self.gate_epsilon.validate(output_data, revenue_strategy, worker_id, metadata):
            return self._create_report(worker_id, False, "Gate Epsilon failed")

        # Gate Zeta
        if not await self.gate_zeta.validate(resource_usage, budget_limit, worker_id, metadata):
            return self._create_report(worker_id, False, "Gate Zeta failed")

        # All gates passed
        try:
            self.memory.update_worker_trust(worker_id, True)
        except Exception as e:
            print(f"[WARNING] Trust update failed: {e}")

        return self._create_report(worker_id, True, "All gates passed")


    def _create_report(self, worker_id: str, passed: bool, message: str) -> Dict[str, Any]:
        """Creates a standardized report."""
        report = {
            "timestamp": datetime.utcnow().isoformat(),
            "worker_id": worker_id,
            "passed": passed,
            "message": message
        }
        try:
            self.memory.log_audit("six_gate_validation", worker_id, report)
        except Exception as e:
            print(f"[WARNING] Audit logging failed: {e}")
        return report

# Example Usage (assuming memory is defined and initialized)
# from aiva.db_connector import memory # Assuming this exists as before

# validator = SixGateValidator()
# async def main():
#     report = await validator.validate_worker_output(
#         input_data="This is the input data.",
#         output_data="The output data follows the format.",
#         task_description="Summarize the input data.",
#         worker_id="worker123",
#         metadata={"some": "data"},
#         expected_format="format",
#         revenue_strategy="increase sales",
#         resource_usage=0.5,
#         budget_limit=1.0,
#         data_to_store={"key": "value"}
#     )
#     print(report)

# if __name__ == "__main__":
#     asyncio.run(main())