
from typing import Dict
from urllib.parse import urljoin
from shared.config import config

def rewrite_nav(nav: Dict[str, Dict], nav_redirects:Dict[str, str]):
    if nav_redirects:
      for label, data in (nav.get("cats") or {}).items():
          top_slug = (data or {}).get("slug")
          if not top_slug:
              continue
          new_subs = []
          for s in (data.get("subs") or []):
              old_sub = (s.get("slug") or "").strip()
              if not old_sub:
                  continue
              old_path = f"/{top_slug}/{old_sub}"
              canonical_path = nav_redirects.get(old_path, old_path)
              parts = [x for x in canonical_path.split("/") if x]
              top2, sub2 = parts[0], parts[1]
              s["slug"] = sub2
              s["href"] = urljoin(config()["base_url"], f"/{top2}/{sub2}")
              new_subs.append(s)
          data["subs"] = new_subs
