from typing import Any

from newspaper import Article

from utils.init import slog
from utils.url import extract_domain


class StatsLoggingCodes:
    SUCCESS = 0
    ERROR = -1
    FORBIDDEN = -2
    TIMEOUT = -3
    UNSUPPORTED = -4
    ERR05 = -5
    ERR06 = -6


def slog_domain(
    status: int,
    url: str,
    track: Any,
    details: Any = "",
    logger_name: str = "stats_log",
) -> None:
    """
    convenience function to log config results in specific format.

    args:
        status: status code (0 for success, non-zero for failure)
        url: URL to test
        track: configuration name/details tracked
        details: Additional details about the result
        logger_name: Name of the logger to use
    """
    if not isinstance(details or "", str):
        details = str(details)
    slog(
        status,
        extract_domain(url),
        track,
        details if (details and url in details) else f"[{url}]: {details or ''}",
        logger_name,
    )


def to_str(
    article: Article, prove_its_useless: bool = True, shorter: bool = True
) -> str:
    """convert article to formatted string representation

    args:
      prove_its_useless: if display potentially unused attributes
      shorter: if exclude verbose content fields
    """
    rc = ""

    attrs = [
        (article.url, "url", "", ""),
        (article.title, "headline", "", ""),
        (article.publish_date, "published", "", ""),
        (article.top_image, "top image", "", ""),
        (article.movies, "videos", "", ""),
        (article.summary, "abstract (nlp)", "", "\n\n"),
        (article.keywords, "keywords (nlp)", "", ""),
        (article.additional_data, "additional_data", "", ""),
        (article.canonical_link, "canonical_link", "", ""),
        (article.download_exception_msg, "download_exception_msg", "", ""),
        (article.meta_description, "meta_description", "", ""),
        (article.meta_img, "meta_img", "", ""),
        (article.meta_keywords, "meta_keywords", "", ""),
        (article.source_url, "source_url", "", ""),
    ]

    if prove_its_useless:
        attrs.extend(
            [
                (article.authors, "authors", "*", ""),
                (article.download_state, "download_state", "*", ""),
                (article.images, "images", "*", ""),
                (article.imgs, "imgs", "*", ""),
                (article.tags, "tags", "*", ""),
                (article.top_img, "top_img", "*", ""),
            ]
        )

    if not shorter:
        attrs.extend(
            [
                (article.text, "content", "", "\n\n"),
                (article.meta_data, "meta_data", "", ""),
            ]
        )

    ws = max(len(attr[1]) for attr in attrs)
    for attr in attrs:
        padding = " " * (ws - len(attr[1]))
        marker = attr[2] or " "
        rc += f"\n{padding}{attr[1]}{marker}:  {attr[3]}{str(attr[0])}"

    return rc
