from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Any

from staticsite.page import AutoPage, ChangeExtent, SourcePage, TemplatePage

from .data import LinkCollection

if TYPE_CHECKING:
    from staticsite.node import Node

    from . import Links

log = logging.getLogger("links")


class LinkIndexPage(TemplatePage, SourcePage):
    """
    Root page for the browseable archive of annotated external links in the
    site
    """

    TYPE = "links_index"
    TEMPLATE = "data-links.html"

    def __init__(
        self,
        *args: Any,
        node: Node,
        links: Links,
        link_collection: LinkCollection,
        **kw: Any,
    ):
        kw.setdefault("nav_title", node.name.capitalize())
        kw.setdefault("title", "All links shared in the site")
        super().__init__(*args, node=node, **kw)
        # Reference to the Feature with the aggregated link collection
        self.feature_links = links
        self.link_collection = link_collection

        self.by_tag: dict[str, LinksTagPage] = {}

    #    def to_dict(self):
    #        from staticsite.utils import dump_meta
    #        res = super().to_dict()
    #        res["name"] = self.name
    #        res["categories"] = dump_meta(self.categories)
    #        res["category_meta"] = dump_meta(self.category_meta)
    #        return res

    def organize(self) -> None:
        pages = []
        for tag, links in self.feature_links.by_tag.items():
            name = tag + "-links"

            if name in self.node.sub:
                # A page already exists
                continue

            page = self.node.create_auto_page_as_path(
                created_from=self,
                name=name,
                page_cls=LinksTagPage,
                data_type="links",
                title=f"{tag} links",
                link_collection=links,
            )
            if page is not None:
                self.by_tag[tag] = page
                pages.append(page)

        # Set self.meta.pages to the sorted list of categories
        pages.sort(key=lambda x: x.title)
        self.pages = pages

    def _compute_change_extent(self) -> ChangeExtent:
        # TODO: with some more infrastructure, we can track what pages
        # contributed the links, and compute something better
        return ChangeExtent.ALL


class LinksTagPage(TemplatePage, AutoPage):
    """
    Page with an autogenerated link collection from a link tag.
    """

    TYPE = "links_tag"
    TEMPLATE = "data-links.html"

    def __init__(self, *args: Any, link_collection: LinkCollection, **kw: Any):
        super().__init__(*args, **kw)
        self.syndicated = False
        self.link_collection = link_collection

    @property
    def src_abspath(self) -> str | None:
        return None

    def _compute_change_extent(self) -> ChangeExtent:
        # TODO: with some more infrastructure, we can track what pages
        # contributed the links, and compute something better
        return ChangeExtent.ALL
