from dataclasses import dataclass
import requests


@dataclass
class CodebergHelper:
    owner: str = "bovine"
    repo: str = "almabtrieb"
    token: str | None = None

    @property
    def repo_base_url(self):
        return f"https://codeberg.org/api/v1/repos/{self.owner}/{self.repo}"

    @property
    def milestone_url(self):
        return f"{self.repo_base_url}/milestones"

    @property
    def release_url(self):
        return f"{self.repo_base_url}/releases"

    def get_milestone_information(self, milestone: str):
        response = requests.get(
            f"{self.milestone_url}?state=open",
            headers={"Authorization": f"Bearer {self.token}"},
        )

        data = response.json()

        for x in data:
            if x.get("title") == milestone:
                return x

        raise ValueError("Milestone not found")

    def close_milestone(self, milestone: str):
        info = self.get_milestone_information(milestone)

        if info.get("open_issues") > 0:
            raise ValueError("Milestone has open issues")

        milestone_id = info.get("id")

        requests.patch(
            f"{self.milestone_url}/{milestone_id}",
            headers={"Authorization": f"Bearer {self.token}"},
            json={"state": "closed"},
        )

        print("milestone closed")

    def create_release(self, milestone: str, body: str):
        response = requests.post(
            self.release_url,
            headers={"Authorization": f"Bearer {self.token}"},
            json={"tag_name": milestone, "name": milestone, "body": body},
        )

        print(response)
        print(response.text)

        print("Created release")
