from __future__ import annotations

from datetime import date

from xdatawork.connect.connectlike import ConnectLike
from xdatawork.connect.connectreflike import ConnectRefLike
from xdatawork.interface.base.interface import BaseInterface
from xdatawork.interface.kind.interface import InterfaceKind
from xdatawork.interface.kind.partition import PartitionKind


class SnapshotDatePartitioned(BaseInterface):
    def __init__(
        self,
        ref: ConnectRefLike,
        connect: ConnectLike,
    ) -> None:
        super().__init__(
            ref=ref,
            connect=connect,
            kind=InterfaceKind.PARTITIONED,
            partitionkind=PartitionKind.SNAPSHOTDATE,
        )

    def list_snapshotdate_refs(self, level: int = 1, levelonly: bool = False) -> list[ConnectRefLike]:
        results = set()
        for ref in self.list_refs():
            parts = ref.strip("/").split("/")
            startrange = level if levelonly else 1
            for i in range(startrange, level + 1):
                if i <= len(parts):
                    sub_path = "/" + "/".join(parts[:i])
                    results.add(sub_path)
        return sorted(list(results))

    def list_snapshotdates(
        self,
        mindate: date | None = None,  # YYYY-MM-DD
        maxdate: date | None = None,  # YYYY-MM-DD
    ) -> list[str]:
        snapshotdates = set()
        for ref in self.list_refs():
            parts = ref.strip("/").split("/")
            if len(parts) >= 1:
                snapshotdate = parts[0]
                if mindate is not None or maxdate is not None:
                    try:
                        sd_date = date.fromisoformat(snapshotdate)
                    except ValueError:
                        continue
                    if mindate is not None and sd_date < mindate:
                        continue
                    if maxdate is not None and sd_date > maxdate:
                        continue
                snapshotdates.add(snapshotdate)
        return sorted(list(snapshotdates))
