"""
Pydantic schemas for AI Agent Tracking model JSONFields.

These schemas validate the JSONFields on AI-related models:
- AgentExecution.input_context, output_result
- HallucinationCheck.input_data, validation_result
- AutomationRun.errors
- BugReport.error_context

Usage:
    from lightwave.schema.pydantic.models.ai import (
        AgentInputContextSchema,
        AgentOutputResultSchema,
        HallucinationInputDataSchema,
        ValidationResultSchema,
        AutomationErrorSchema,
        BugReportContextSchema,
    )
"""

from typing import Any

from pydantic import Field

from lightwave.schema.pydantic.core.base import JSONFieldSchema


class AgentInputContextSchema(JSONFieldSchema):
    """
    Schema for AgentExecution.input_context JSONField.

    Context provided to an agent when it executes a task.
    Contains task details, relevant data, and configuration.

    Example:
        {
            "task_id": "abc1234",
            "task_title": "Implement billing dashboard",
            "task_type": "feature",
            "story_context": {...},
            "relevant_files": ["src/billing/views.py"],
            "user_preferences": {}
        }
    """

    task_id: str | None = Field(None, description="Task identifier")
    task_title: str | None = Field(None, description="Task title")
    task_type: str | None = Field(None, description="Type of task (feature, fix, etc.)")
    story_context: dict[str, Any] | None = Field(None, description="Related user story context")
    relevant_files: list[str] = Field(default_factory=list, description="List of relevant file paths")
    user_preferences: dict[str, Any] = Field(default_factory=dict, description="User preferences for agent behavior")
    additional_context: dict[str, Any] = Field(default_factory=dict, description="Any additional context data")


class AgentOutputResultSchema(JSONFieldSchema):
    """
    Schema for AgentExecution.output_result JSONField.

    Structured output from an agent execution.
    Contains the results, artifacts, and metadata from the run.

    Example:
        {
            "status": "success",
            "artifacts": [{"type": "file", "path": "src/billing.py"}],
            "summary": "Created billing dashboard component",
            "metrics": {"lines_added": 150, "files_changed": 3},
            "suggestions": []
        }
    """

    status: str | None = Field(None, description="Execution status")
    artifacts: list[dict[str, Any]] = Field(default_factory=list, description="Generated artifacts (files, code, etc.)")
    summary: str | None = Field(None, description="Summary of what was accomplished")
    metrics: dict[str, Any] = Field(default_factory=dict, description="Execution metrics")
    suggestions: list[str] = Field(default_factory=list, description="Suggestions for follow-up actions")
    warnings: list[str] = Field(default_factory=list, description="Warnings generated during execution")


class HallucinationInputDataSchema(JSONFieldSchema):
    """
    Schema for HallucinationCheck.input_data JSONField.

    Data that was validated during a hallucination gate check.
    Contains the content being verified and its source.

    Example:
        {
            "content_type": "code",
            "content": "def calculate_total(items): ...",
            "source": "agent_output",
            "references": ["src/billing/utils.py:45"]
        }
    """

    content_type: str | None = Field(None, description="Type of content (code, fact, data)")
    content: str | None = Field(None, description="The actual content being checked")
    source: str | None = Field(None, description="Where the content came from")
    references: list[str] = Field(default_factory=list, description="References to verify against")
    context: dict[str, Any] = Field(default_factory=dict, description="Additional context for verification")


class ValidationResultSchema(JSONFieldSchema):
    """
    Schema for HallucinationCheck.validation_result JSONField.

    Detailed results from a hallucination validation check.
    Contains findings, confidence scores, and recommendations.

    Example:
        {
            "is_valid": true,
            "confidence": 0.95,
            "findings": [{"type": "syntax_valid", "details": "..."}],
            "issues": [],
            "recommendations": []
        }
    """

    is_valid: bool | None = Field(None, description="Whether validation passed")
    confidence: float | None = Field(None, ge=0.0, le=1.0, description="Confidence score (0-1)")
    findings: list[dict[str, Any]] = Field(default_factory=list, description="Detailed findings from validation")
    issues: list[dict[str, Any]] = Field(default_factory=list, description="Issues found during validation")
    recommendations: list[str] = Field(default_factory=list, description="Recommendations based on validation")


class AutomationErrorSchema(JSONFieldSchema):
    """
    Schema for individual error in AutomationRun.errors JSONField list.

    Represents a single error encountered during an automation run.

    Example:
        {
            "error_type": "ValidationError",
            "message": "Invalid task format",
            "task_id": "abc1234",
            "timestamp": "2024-01-15T10:30:00Z",
            "is_recoverable": true
        }
    """

    error_type: str = Field(..., description="Type/class of the error")
    message: str = Field(..., description="Error message")
    task_id: str | None = Field(None, description="Task that caused the error")
    timestamp: str | None = Field(None, description="When the error occurred (ISO 8601)")
    is_recoverable: bool = Field(True, description="Whether the error is recoverable")
    stack_trace: str | None = Field(None, description="Stack trace if available")
    context: dict[str, Any] = Field(default_factory=dict, description="Additional error context")


class BugReportContextSchema(JSONFieldSchema):
    """
    Schema for BugReport.error_context JSONField.

    Context around a bug detected during agent execution.
    Contains inputs, state, and environment information.

    Example:
        {
            "agent_type": "v_developer",
            "input_request": "Fix the login redirect bug",
            "execution_state": {"step": 3, "action": "code_generation"},
            "environment": {"python_version": "3.11", "django_version": "5.1"},
            "recent_actions": ["read_file", "analyze_code", "generate_fix"]
        }
    """

    agent_type: str | None = Field(None, description="Agent that encountered the bug")
    input_request: str | None = Field(None, description="Original input that triggered the bug")
    execution_state: dict[str, Any] = Field(default_factory=dict, description="State at time of error")
    environment: dict[str, Any] = Field(default_factory=dict, description="Environment information")
    recent_actions: list[str] = Field(default_factory=list, description="Recent actions before the error")
    related_files: list[str] = Field(default_factory=list, description="Files involved in the error")
