from __future__ import annotations

from typing import Any

from zvondb.client import RegistryClient
from zvondb.models import ExperimentInfo, ProjectInfo


class Experiment:
    """Handle to an experiment within a project. Used to start jobs."""

    def __init__(
        self,
        client: RegistryClient,
        project: str,
        name: str,
        project_info: ProjectInfo | None = None,
    ):
        self._client = client
        self._project = project
        self._name = name
        self._project_info = project_info

    @property
    def name(self) -> str:
        return self._name

    def info(self) -> ExperimentInfo:
        data = self._client.get(
            f"/projects/{self._project}/experiments/{self._name}"
        )
        return ExperimentInfo(**data)

    def start_job(
        self,
        name: str,
        git_sha: str,
        metadata: dict[str, Any] | None = None,
        tracking_url: str | None = None,
    ) -> "Job":
        from zvondb.job import Job

        data = self._client.post(
            f"/projects/{self._project}/jobs",
            json={
                "name": name,
                "experiment": self._name,
                "git_sha": git_sha,
                "metadata": metadata or {},
                "tracking_url": tracking_url,
            },
        )
        return Job(
            client=self._client,
            project=self._project,
            experiment=self._name,
            job_id=data["id"],
            project_info=self._project_info,
        )
