# gophian -- tools to help with Debianizing Go software
# Copyright (C) 2024-2025 Maytham Alsudany <maytha8thedev@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from typing import List, Optional, Self
from datetime import datetime

import requests
from debian.deb822 import Deb822


class NewPackage:
    """
    A package in the ftpmaster's NEW queue.
    """

    def __init__(self, stanza: Deb822) -> None:
        self.source: str = stanza["Source"]
        self.binary: List[str] = list(
            filter(lambda b: not b.endswith("-dbgsym"), stanza["Binary"].split(", "))
        )
        self.version: str = stanza["Version"]
        self.architectures: List[str] = stanza["Architectures"].split(", ")
        self.age: str = stanza["Age"]
        self.last_modified: datetime = datetime.fromtimestamp(
            int(stanza["Last-Modified"])
        )
        self.queue: str = stanza["Queue"]
        self.maintainer: str = stanza["Maintainer"]
        self.changed_by: str = stanza["Changed-By"]
        self.distribution: str = stanza["Distribution"]
        self.fingerprint: str = stanza["Fingerprint"]
        self.closes: List[str] = (
            stanza["Closes"].split(", ") if "Closes" in stanza else []
        )
        self.url: str = (
            "https://ftp-master.debian.org/new/"
            + self.source
            + "_"
            + self.version
            + ".html"
        )

    @classmethod
    def all(cls, session: requests.Session) -> List[Self]:
        text = session.get("https://ftp-master.debian.org/new.822", timeout=60).text
        new_packages: List[Self] = []
        for stanza in Deb822.iter_paragraphs(text):
            new_packages.append(cls(stanza))
        return list(filter(lambda p: p.queue == "new", new_packages))

    @classmethod
    def get(cls, session: requests.Session, source_package: str) -> Optional[Self]:
        packages = cls.all(session)
        for package in packages:
            if package.source == source_package:
                return package
        return None
