"""Insight Correlation database model for cross-service intelligence."""

from sqlalchemy import Column, String, Integer, DECIMAL, TIMESTAMP, ForeignKey, Index
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
import uuid

from app.core.database import Base


class InsightCorrelation(Base):
    """Track correlations between insights from different services."""

    __tablename__ = "insight_correlations"

    # Primary Key
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)

    # Foreign Keys to AIInsights
    parent_insight_id = Column(
        UUID(as_uuid=True),
        ForeignKey('ai_insights.id', ondelete='CASCADE'),
        nullable=False,
        index=True,
        comment="Primary insight that leads to correlation"
    )
    child_insight_id = Column(
        UUID(as_uuid=True),
        ForeignKey('ai_insights.id', ondelete='CASCADE'),
        nullable=False,
        index=True,
        comment="Related insight"
    )

    # Correlation Information
    correlation_type = Column(
        String(50),
        nullable=False,
        comment="forecast_inventory, production_procurement, weather_customer, demand_supplier, etc."
    )
    correlation_strength = Column(
        DECIMAL(3, 2),
        nullable=False,
        comment="0.00 to 1.00 indicating strength of correlation"
    )

    # Combined Metrics
    combined_confidence = Column(
        Integer,
        comment="Weighted combined confidence of both insights"
    )

    # Timestamp
    created_at = Column(
        TIMESTAMP(timezone=True),
        server_default=func.now(),
        nullable=False,
        index=True
    )

    # Composite Indexes
    __table_args__ = (
        Index('idx_parent_child', 'parent_insight_id', 'child_insight_id'),
        Index('idx_correlation_type', 'correlation_type'),
    )

    def __repr__(self):
        return f"<InsightCorrelation(id={self.id}, type={self.correlation_type}, strength={self.correlation_strength})>"
