import time
from datetime import datetime
from typing import Dict

from debian.changelog import Changelog

from debputy.util import _warn, _error


def load_source_variables(changelog_file: str) -> Dict[str, str]:
    with open(changelog_file) as fd:
        dch = Changelog(fd, max_blocks=2)
    first_entry = dch[0]
    first_non_binnmu_entry = dch[0]
    if first_non_binnmu_entry.other_pairs.get("binary-only", "no") == "yes":
        first_non_binnmu_entry = dch[1]
        assert first_non_binnmu_entry.other_pairs.get("binary-only", "no") == "no"
    source_version = first_entry.version
    epoch = source_version.epoch
    upstream_version = source_version.upstream_version
    debian_revision = source_version.debian_revision
    epoch_upstream = upstream_version
    upstream_debian_revision = upstream_version
    if epoch is not None and epoch != "":
        epoch_upstream = f"{epoch}:{upstream_version}"
    if debian_revision is not None and debian_revision != "":
        upstream_debian_revision = f"{upstream_version}-{debian_revision}"

    package = first_entry.package
    if package is None:
        _error("Cannot determine the source package name from debian/changelog.")

    date = first_entry.date
    if date is not None:
        local_time = datetime.strptime(date, "%a, %d %b %Y %H:%M:%S %z")
        source_date_epoch = str(int(local_time.timestamp()))
    else:
        _warn(
            "The latest changelog entry does not have a (parsable) date, using current time"
            " for SOURCE_DATE_EPOCH"
        )
        source_date_epoch = str(int(time.time()))
    return {
        "DEB_SOURCE": package,
        "DEB_VERSION": source_version.full_version,
        "DEB_VERSION_EPOCH_UPSTREAM": epoch_upstream,
        "DEB_VERSION_UPSTREAM_REVISION": upstream_debian_revision,
        "DEB_VERSION_UPSTREAM": upstream_version,
        "SOURCE_DATE_EPOCH": source_date_epoch,
        "_DEBPUTY_INTERNAL_NON_BINNMU_SOURCE": first_non_binnmu_entry.version,
    }
