from pelican import signals
import logging
import os

logger = logging.getLogger(__name__)
from pelican.settings import DEFAULT_CONFIG


def set_default_settings(settings):
    settings.setdefault("GIT_SOURCE_BASE_URL", None)


def init_default_config(pelican):
    set_default_settings(DEFAULT_CONFIG)
    if pelican:
        set_default_settings(pelican.settings)


def source_link_generator(article_generator):
    git_source = article_generator.settings.get(
        "GIT_SOURCE_BASE_URL", DEFAULT_CONFIG["GIT_SOURCE_BASE_URL"]
    )
    root_path = article_generator.settings.get("PATH", DEFAULT_CONFIG.get("PATH", ""))
    for article in article_generator.articles:
        article_path = os.path.abspath(os.path.join(root_path, article.source_path))
        relative_path = os.path.relpath(article_path, root_path)
        if git_source.endswith("/"):
            article.source_link = f"{git_source}{relative_path}"
        else:
            article.source_link = f"{git_source}/{relative_path}"

        article.path_source_link = "/".join(article.source_link.split("/")[:-1])


def register():
    signals.initialized.connect(init_default_config)
    signals.article_generator_finalized.connect(source_link_generator)
