from __future__ import annotations

from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, ConfigDict, Field


class ScanRequest(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    prompt: str
    categories: List[str] = Field(..., description="Selected scan categories")
    title: Optional[str] = None
    description: Optional[str] = None
    model: Optional[str] = None
    user_id: Optional[str] = Field(None, alias="userId")


class IssueDetail(BaseModel):
    id: str
    group: str
    level: str
    description: Optional[str] = None


class FirewallGroupResult(BaseModel):
    group: str
    results: List[Dict[str, Any]] = Field(default_factory=list)
    blocked: int = 0
    total: int = 0


class ScanResult(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    issues: List[IssueDetail] = Field(default_factory=list)
    firewall_results: List[FirewallGroupResult] = Field(
        default_factory=list,
        alias="firewallResults",
    )
    timestamp: datetime = Field(default_factory=datetime.utcnow)
    credits_used: int = Field(0, alias="creditsUsed")


class ScanJobStatus(str, Enum):
    QUEUED = "queued"
    PROCESSING = "processing"
    COMPLETED = "completed"
    FAILED = "failed"


class ScanJob(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    job_id: str = Field(..., alias="jobId")
    status: ScanJobStatus
    prompt: str
    categories: List[str]
    queued_at: datetime = Field(..., alias="queuedAt")
    started_at: Optional[datetime] = Field(None, alias="startedAt")
    completed_at: Optional[datetime] = Field(None, alias="completedAt")
    result: Optional[ScanResult] = None
    error_message: Optional[str] = Field(None, alias="errorMessage")
