"""
SQLAlchemy models for metrics and contract violations.

Designed to work with both SQLite and PostgreSQL (Azure).
"""

from sqlalchemy import JSON, Boolean, Column, DateTime, Float, Index, Integer, String
from sqlalchemy.sql import func

from .database import Base


class MetricRecord(Base):
    """
    Store performance metrics for contract validations.
    """

    __tablename__ = "metrics"

    id = Column(Integer, primary_key=True, index=True)
    agent_id = Column(String, nullable=False, index=True)
    contract_id = Column(String, nullable=False, index=True)
    timestamp = Column(DateTime(timezone=True), server_default=func.now(), index=True)

    # Performance metrics
    validation_time_ms = Column(Float, nullable=False)
    token_count = Column(Integer)
    cache_hit = Column(Boolean, default=False)

    # Response metrics
    confidence_score = Column(Float)
    temperature_used = Column(Float)

    # Additional context
    extra_data = Column(JSON)  # Flexible field for extra data

    # Indexes for common queries
    __table_args__ = (
        Index("idx_agent_timestamp", "agent_id", "timestamp"),
        Index("idx_contract_timestamp", "contract_id", "timestamp"),
    )


class ContractViolation(Base):
    """
    Track contract violations and security events.
    """

    __tablename__ = "violations"

    id = Column(Integer, primary_key=True, index=True)
    violation_id = Column(String, nullable=False, unique=True, index=True)
    agent_id = Column(String, nullable=False, index=True)
    contract_id = Column(String, nullable=False, index=True)
    timestamp = Column(DateTime(timezone=True), server_default=func.now(), index=True)

    # Violation details
    violation_type = Column(
        String, nullable=False, index=True
    )  # e.g., "prompt_injection", "hallucination"
    severity = Column(String, nullable=False)  # "low", "medium", "high", "critical"
    confidence = Column(Float, nullable=False)  # Detection confidence

    # Context
    input_data = Column(JSON)
    output_data = Column(JSON)
    detection_details = Column(JSON)  # Specific details about what was detected

    # Resolution
    resolved = Column(Boolean, default=False, index=True)
    resolution_notes = Column(String)
    resolved_at = Column(DateTime(timezone=True))

    # Indexes for security queries
    __table_args__ = (
        Index("idx_unresolved_violations", "resolved", "severity", "timestamp"),
        Index("idx_violation_type_time", "violation_type", "timestamp"),
    )


class AgentPerformance(Base):
    """
    Aggregated performance statistics per agent.

    Updated periodically from raw metrics for dashboard display.
    """

    __tablename__ = "agent_performance"

    id = Column(Integer, primary_key=True, index=True)
    agent_id = Column(String, nullable=False, unique=True, index=True)
    last_updated = Column(DateTime(timezone=True), server_default=func.now())

    # Aggregated metrics
    total_validations = Column(Integer, default=0)
    avg_validation_time_ms = Column(Float)
    p95_validation_time_ms = Column(Float)
    p99_validation_time_ms = Column(Float)

    # Cache performance
    cache_hit_rate = Column(Float)
    total_cache_hits = Column(Integer, default=0)

    # Token usage
    total_tokens = Column(Integer, default=0)
    avg_tokens_per_request = Column(Float)

    # Violations
    total_violations = Column(Integer, default=0)
    critical_violations = Column(Integer, default=0)
    high_violations = Column(Integer, default=0)

    # Compliance
    compliance_score = Column(Float)  # 0.0 to 1.0
    last_violation_timestamp = Column(DateTime(timezone=True))

    # Additional stats
    extra_data = Column(JSON)
