"""
AI Framework Models
"""
from django.db import models
from igny8_core.auth.models import AccountBaseModel


class AITaskLog(AccountBaseModel):
    """
    Unified logging table for all AI tasks.
    Stores request/response steps, costs, tokens, and results.
    """
    task_id = models.CharField(max_length=255, db_index=True, null=True, blank=True)
    function_name = models.CharField(max_length=100, db_index=True)
    phase = models.CharField(max_length=50, default='INIT')
    message = models.TextField(blank=True)
    status = models.CharField(max_length=20, choices=[
        ('success', 'Success'),
        ('error', 'Error'),
        ('pending', 'Pending'),
    ], default='pending')
    
    # Timing
    duration = models.IntegerField(null=True, blank=True, help_text="Duration in milliseconds")
    
    # Cost tracking
    cost = models.DecimalField(max_digits=10, decimal_places=6, default=0.0)
    tokens = models.IntegerField(default=0)
    
    # Step tracking
    request_steps = models.JSONField(default=list, blank=True)
    response_steps = models.JSONField(default=list, blank=True)
    
    # Error tracking
    error = models.TextField(null=True, blank=True)
    
    # Data
    payload = models.JSONField(null=True, blank=True)
    result = models.JSONField(null=True, blank=True)
    
    class Meta:
        db_table = 'igny8_ai_task_logs'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['task_id']),
            models.Index(fields=['function_name', 'account']),
            models.Index(fields=['status', 'created_at']),
        ]
    
    def __str__(self):
        return f"{self.function_name} - {self.status} - {self.created_at}"

