#!/usr/bin/env python

"""████
 ██    ██    Datature
   ██  ██    Powering Breakthrough AI
     ██

@File    :   responses.py
@Author  :   Wei Loon Cheng
@Contact :   developers@datature.io
@License :   Apache License 2.0
@Desc    :   Datature Vi SDK training projects responses module.
"""

from datetime import datetime
from typing import Any

from msgspec import field
from vi.api.responses import ResourceMetadata, ViResponse


class TrainingProjectSpec(ViResponse):
    """Training project spec.

    Attributes:
        name: Display name of the training project.
        description: Optional description of the training project.
        type: Project type - one of "phrase-grounding", "vqa", or "freeform".

    """

    name: str
    description: str | None = None
    type: str = ""


class TrainingProjectStatus(ViResponse):
    """Training project status.

    Attributes:
        runs: List of run IDs associated with this project.
        flows: List of flow IDs associated with this project.
        run_outputs: List of run output IDs.
        tasks: List of tasks.

    """

    runs: list[str] = field(default_factory=list)
    flows: list[str] = field(default_factory=list)
    run_outputs: list[str] = field(default_factory=list)
    tasks: list[Any] = field(default_factory=list)


class TrainingProject(ViResponse, tag_field="kind"):
    """Training project.

    Attributes:
        organization_id: Organization ID.
        training_project_id: Unique identifier for the training project.
        spec: Training project specification.
        status: Training project status with associated runs/flows.
        metadata: Resource metadata including timestamps.
        self_link: API link to this training project resource.
        etag: Entity tag for caching and concurrency control.

    """

    organization_id: str = field(name="workspaceId")
    training_project_id: str
    spec: TrainingProjectSpec
    status: TrainingProjectStatus
    metadata: ResourceMetadata
    self_link: str
    etag: str

    def info(self) -> None:
        """Display rich information about this training project.

        Shows a formatted summary of the training project including
        spec, status, and metadata in an easy-to-read format.

        Example:
            ```python
            project = client.training_projects.get(training_project_id="project_abc123")
            project.info()
            ```

        """
        created_str = datetime.fromtimestamp(
            self.metadata.time_created / 1000
        ).strftime("%Y-%m-%d %H:%M:%S")
        updated_str = datetime.fromtimestamp(
            self.metadata.last_updated / 1000
        ).strftime("%Y-%m-%d %H:%M:%S")

        info_text = f"""
Training Project Information

  BASIC INFO:
   Project ID:     {self.training_project_id}
   Name:           {self.spec.name}
   Description:    {self.spec.description or "Not specified"}
   Type:           {self.spec.type}
   Organization:   {self.organization_id}

  STATUS:
   Runs:           {len(self.status.runs)} run(s)
   Flows:          {len(self.status.flows)} flow(s)
   Run Outputs:    {len(self.status.run_outputs)} output(s)

  DATES:
   Created:        {created_str}
   Last Updated:   {updated_str}

  QUICK ACTIONS:
   Delete:      client.training_projects.delete(training_project_id="{self.training_project_id}")
   Update:      client.training_projects.update(training_project_id="{self.training_project_id}", spec={{...}})
"""
        print(info_text)


class AggregationInsightsPayload(ViResponse):
    """Aggregation insights payload.

    Attributes:
        results: Dictionary of aggregation results keyed by run ID.
        time_updated: Timestamp of last update.

    """

    results: dict[str, Any] = field(default_factory=dict)
    time_updated: str | None = None


class PendingOperation(ViResponse):
    """Pending operation for aggregation insights.

    Attributes:
        status: Status of the pending operation.
        time_initiated: Timestamp when the operation was initiated.

    """

    status: str
    time_initiated: str | None = None


class AggregationInsightsResult(ViResponse):
    """Aggregation insights result.

    Attributes:
        payload: Optional aggregation results payload.
        pending_operation: Optional pending operation status.

    """

    payload: AggregationInsightsPayload | None = None
    pending_operation: PendingOperation | None = None


class DryRunError(ViResponse):
    """Dry run error.

    Attributes:
        kind: Error kind - "IdConflict" or "NameConflict".

    """

    kind: str


class DryRunResponse(ViResponse):
    """Dry run response.

    Attributes:
        errors: List of validation errors from the dry run.

    """

    errors: list[DryRunError] = field(default_factory=list)
