from typing import Optional

from .._http import HttpClient
from .._environment import Environment
from ..models.project import Project, ProjectList


class ProjectsNamespace:
    def __init__(self, http: HttpClient):
        self._http = http

    def create(
        self,
        name: str,
        description: Optional[str] = None,
        environment: str = "railway",
    ) -> Project:
        data = self._http.post("/jobs/init", json={
            "job_name": name,
            "description": description or "",
            "is_default": False,
            "environment": environment,
        })
        return Project(
            job_name=data.get("job_name", name),
            description=description,
        )

    def list(self, environment: str = "railway") -> ProjectList:
        params = {"environment": environment} if environment else None
        data = self._http.get("/jobs", params=params)
        return ProjectList.from_dict(data)

    def get(self, name: str) -> Project:
        data = self._http.get(f"/jobs/{name}")
        return Project.from_dict({
            "job_name": data.get("job_name", name),
            "description": data.get("description"),
            "created_at": data.get("created_at"),
            "jobs": data.get("jobs"),
        })

