"""Parse sitemap.xml and sitemap index files (sitemaps.org protocol)."""

from __future__ import annotations

import xml.etree.ElementTree as ET
from typing import List, Tuple

NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"


def parse_sitemap(xml_text: str) -> Tuple[List[Tuple[str, str]], List[str]]:
    """Return (pages, child_sitemaps). pages = [(loc, lastmod)].

    Note: xml.etree is not hardened against malicious XML (entity expansion);
    only parse sitemaps from sites you chose to crawl, and cap their size.
    """
    root = ET.fromstring(xml_text.strip())
    pages, children = [], []
    tag = root.tag.replace(NS, "")
    if tag == "urlset":
        for u in root.iter(f"{NS}url"):
            loc = (u.findtext(f"{NS}loc") or "").strip()
            if loc:
                pages.append((loc, (u.findtext(f"{NS}lastmod") or "").strip()))
    elif tag == "sitemapindex":
        for s in root.iter(f"{NS}sitemap"):
            loc = (s.findtext(f"{NS}loc") or "").strip()
            if loc:
                children.append(loc)
    return pages, children
