from datetime import datetime
from typing import Dict

from debian.changelog import Changelog


def load_source_variables(changelog_file: str) -> Dict[str, str]:
    with open(changelog_file) as fd:
        dch = Changelog(fd, max_blocks=1)
    first_entry = dch[0]
    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}"

    local_time = datetime.strptime(first_entry.date, "%a, %d %b %Y %H:%M:%S %z")
    source_date_epoch = str(int(local_time.timestamp()))
    return {
        "DEB_SOURCE": first_entry.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,
    }
