# coding: utf-8

"""
    Qoetry API

    Qoetry API for dataset collection and management. Start dataset collection jobs, monitor their progress, and download results as CSV files.  ## Authentication  **All endpoints require API key authentication** (except `/health` and `/`).  You can provide your API key via: - Query parameter: `?api_key=your_api_key` - Header: `x-api-key: your_api_key` - Header: `Authorization: Bearer your_api_key`  ## Rate Limits  API calls are subject to monthly quotas based on your subscription plan. Quota information is available via the `/v0/usage` endpoint. 

    The version of the OpenAPI document: 0.5.0
    Contact: samuel.tinnerholm@gmail.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List
from typing_extensions import Annotated
from qoery.models.get_dataset_job_status200_response_progress import GetDatasetJobStatus200ResponseProgress
from typing import Optional, Set
from typing_extensions import Self

class JobStatus(BaseModel):
    """
    Complete status information for a dataset collection job
    """ # noqa: E501
    job_id: Annotated[str, Field(strict=True)] = Field(description="Unique identifier for the job")
    status: StrictStr = Field(description="Current job status. Possible values: - `processing`: Job is actively collecting and processing data - `completed`: Job finished successfully, CSV is ready for download - `error`: Job failed, check the `error` field for details ")
    query: StrictStr = Field(description="Original search query")
    progress: GetDatasetJobStatus200ResponseProgress
    urls: List[StrictStr] = Field(description="List of URLs being processed")
    csv_url: StrictStr = Field(description="URL to download the CSV file")
    error: StrictStr = Field(description="Error message if status is 'error'")
    started_at: datetime = Field(description="Timestamp when the job started")
    completed_at: datetime = Field(description="Timestamp when the job completed (null if still processing)")
    __properties: ClassVar[List[str]] = ["job_id", "status", "query", "progress", "urls", "csv_url", "error", "started_at", "completed_at"]

    @field_validator('job_id')
    def job_id_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if not re.match(r"^[0-9]{8}_[0-9]{6}$", value):
            raise ValueError(r"must validate the regular expression /^[0-9]{8}_[0-9]{6}$/")
        return value

    @field_validator('status')
    def status_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['processing', 'completed', 'error']):
            raise ValueError("must be one of enum values ('processing', 'completed', 'error')")
        return value

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of JobStatus from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of progress
        if self.progress:
            _dict['progress'] = self.progress.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of JobStatus from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "job_id": obj.get("job_id"),
            "status": obj.get("status"),
            "query": obj.get("query"),
            "progress": GetDatasetJobStatus200ResponseProgress.from_dict(obj["progress"]) if obj.get("progress") is not None else None,
            "urls": obj.get("urls"),
            "csv_url": obj.get("csv_url"),
            "error": obj.get("error"),
            "started_at": obj.get("started_at"),
            "completed_at": obj.get("completed_at")
        })
        return _obj


