"""Human-readable part-type labels.

Source of truth = the labels used in the legacy site's parts navigation
(`site/partsnav.tmpl`) — deliberately the SHORT nav forms (e.g. "BCGs &
Parts", "Complete Uppers"), not the longer `%page_type` descriptions in
`instock/index.cgi`. Keyed by the DB `parts.type` short code so templates
can render `{{ p.type|type_label }}` instead of the raw code.

Unknown/legacy codes fall back to the raw code so nothing renders blank.
"""

TYPE_LABELS = {
    # Lower parts
    "strippedlower": "Stripped Lowers",
    "completelower": "Complete Lowers",
    "upperlower": "Upper/Lower Sets",
    "lpk": "Lower Parts Kits",
    "lprt": "Small Parts",
    "lbk": "Lower Build Kits",
    "trigger": "Triggers",
    "grip": "Grips",
    "stock": "Stocks",
    "buffer": "Buffers",
    "mag": "Mags",
    # Upper parts
    "strippedupper": "Stripped Uppers",
    "completeupper": "Complete Uppers",
    "bcg": "BCGs & Parts",
    "barrel": "Barrels",
    "muzzle": "Muzzle Devices",
    "ch": "Charging Handles",
    "rail": "Rails/Guards",
    "gasblock": "Gas Blocks",
    "gastube": "Gas Tubes",
    "sight": "Sights",
    "optic": "Optics",
    # Other
    "tool": "Tools",
    "clean": "Cleaning",
    # Ammo (nav links offsite, but the codes can appear on rows)
    "223ammo": ".223 Ammo",
    "22ammo": ".22LR Ammo",
}


def type_label(code: str) -> str:
    """DB type code -> short nav label; falls back to the code itself."""
    return TYPE_LABELS.get(code, code)


# Singular form of each type label, for count-aware rendering (e.g.
# "Complete Lower" for a build with one of that type, "Complete
# Lowers" for two+). Used by `type_label_for_count` below. Most are
# trivial drop-the-trailing-s, but a few are judgment calls
# (BCGs & Parts -> BCG drops the awkward conjunction; Rails/Guards
# -> Rail/Guard pluralizes correctly on both sides; mass nouns like
# Cleaning / Ammo don't pluralize).
TYPE_LABELS_SINGULAR = {
    # Lower parts
    "strippedlower": "Stripped Lower",
    "completelower": "Complete Lower",
    "upperlower": "Upper/Lower Set",
    "lpk": "Lower Parts Kit",
    "lprt": "Small Part",
    "lbk": "Lower Build Kit",
    "trigger": "Trigger",
    "grip": "Grip",
    "stock": "Stock",
    "buffer": "Buffer",
    "mag": "Mag",
    # Upper parts
    "strippedupper": "Stripped Upper",
    "completeupper": "Complete Upper",
    "bcg": "BCG",
    "barrel": "Barrel",
    "muzzle": "Muzzle Device",
    "ch": "Charging Handle",
    "rail": "Rail/Guard",
    "gasblock": "Gas Block",
    "gastube": "Gas Tube",
    "sight": "Sight",
    "optic": "Optic",
    # Other
    "tool": "Tool",
    "clean": "Cleaning",       # mass noun, no plural change anyway
    # Ammo (mass nouns)
    "223ammo": ".223 Ammo",
    "22ammo": ".22LR Ammo",
}


def type_label_for_count(code: str, count: int) -> str:
    """Count-aware type label. Returns the singular form when count==1,
    the plural form otherwise. Falls back to the plural label if no
    singular is defined, and to the raw code if neither is defined."""
    if count == 1:
        return TYPE_LABELS_SINGULAR.get(
            code, TYPE_LABELS.get(code, code))
    return TYPE_LABELS.get(code, code)


# Per-type SEO meta descriptions for the /browse?type=<code> long-tail
# landing pages. Each ~140-160 chars, written for the actual shopper
# query intent: include the type name, "AR-15 and AR-10" where the
# part applies to both platforms, and a few of the specific keywords
# people actually search (brand names, mil-spec variants, attachment
# standards). Per docs/seo.md §C — each type-filter page is its own
# long-tail landing page and earns its own description.
#
# Unknown / unmapped codes fall through to the generic description in
# browse.html (see type_description() below).
TYPE_META_DESCRIPTIONS = {
    # Lower parts
    "strippedlower": "AR-15 and AR-10 stripped lower receivers in stock at US retailers. Live prices and FFL-ready inventory. Compare and buy direct.",
    "completelower": "Complete AR-15 and AR-10 lower assemblies in stock, FFL-ready. Compare prices and availability across US retailers. ARPartsFinder.",
    "upperlower":    "Matched AR-15 and AR-10 upper/lower receiver sets in stock at US retailers. Live prices, compare and buy direct from whoever has them.",
    "lpk":           "AR-15 and AR-10 lower parts kits (LPK) in stock at US retailers: complete kits and mil-spec components. Live prices and restock alerts.",
    "lprt":          "AR-15 and AR-10 small parts in stock at US retailers: takedown pins, springs, detents, selectors, dust covers, port doors, end plates and more. Live prices and restock alerts.",
    "lbk":           "AR-15 and AR-10 lower build kits in stock: ready-to-assemble parts bundles. Live prices across US retailers. ARPartsFinder.",
    "trigger":       "AR-15 and AR-10 triggers in stock at US retailers: drop-in, two-stage, single-stage, mil-spec upgrades. Live prices and restock alerts.",
    "grip":          "AR-15 and AR-10 pistol grips in stock at US retailers: Magpul, BCM, Hogue, ergonomic and angled options. Live prices, compare direct.",
    "stock":         "AR-15 and AR-10 buttstocks in stock at US retailers: collapsible, fixed, precision, B5 and Magpul options. Live prices and restock alerts.",
    "buffer":        "AR-15 and AR-10 buffers and buffer kits in stock at US retailers: carbine, H, H2, H3, rifle weight. Live prices, compare and buy direct.",
    "mag":           "AR-15 and AR-10 magazines in stock at US retailers: Magpul PMAG, Lancer, mil-spec, all common calibers. Live prices and restock alerts.",
    # Upper parts
    "strippedupper": "AR-15 and AR-10 stripped upper receivers in stock at US retailers. Live prices, restock detection. Compare and buy direct. ARPartsFinder.",
    "completeupper": "Complete AR-15 and AR-10 upper assemblies in stock: BCG, barrel, handguard, charging handle pre-installed. Live prices at US retailers.",
    "bcg":           "AR-15 and AR-10 bolt carrier groups (BCGs) in stock at US retailers: mil-spec, NiB, full-auto profile. Live prices and restock alerts.",
    "barrel":        "AR-15 and AR-10 barrels in stock at US retailers: every length and profile, 5.56, .223 Wylde, .308, 6.5 Creedmoor, more. Live prices.",
    "muzzle":        "AR-15 and AR-10 muzzle devices in stock at US retailers: flash hiders, compensators, brakes, suppressor mounts. Live prices, compare direct.",
    "ch":            "AR-15 and AR-10 charging handles in stock at US retailers: BCM Gunfighter, Radian Raptor, mil-spec, ambidextrous. Live prices.",
    "rail":          "AR-15 and AR-10 handguards and rails in stock at US retailers: M-LOK, KeyMod, free-float, drop-in. Live prices, restock alerts.",
    "gasblock":      "AR-15 and AR-10 gas blocks in stock at US retailers: low-profile, clamp-on, adjustable, set-screw. Live prices, compare direct.",
    "gastube":       "AR-15 and AR-10 gas tubes in stock at US retailers: pistol, carbine, mid-length, rifle length. Live prices, compare and buy direct.",
    "sight":         "AR-15 and AR-10 iron sights in stock at US retailers: front, rear, flip-up, fixed BUIS, co-witness compatible. Live prices, restock alerts.",
    "optic":         "AR-15 and AR-10 optics in stock at US retailers: red dots, holographic, LPVO, magnified scopes. Live prices and restock detection.",
    # Other
    "tool":          "AR-15 and AR-10 armorer tools and bench gear in stock: vise blocks, wrenches, punch sets, gauges. Live prices across US retailers.",
    "clean":         "AR-15 and AR-10 cleaning supplies in stock at US retailers: kits, brushes, solvents, lubricants. Live prices, compare and buy direct.",
    # Ammo codes can appear on rows but the nav links offsite, so these
    # landing pages may not be reachable. Descriptions included as a
    # safety net.
    "223ammo":       ".223 Remington and 5.56 NATO ammunition in stock for AR-15 platforms. Live prices across US retailers. ARPartsFinder.",
    "22ammo":        ".22 LR ammunition in stock for AR-15 conversion uppers and trainers. Live prices across US retailers. ARPartsFinder.",
}


def type_description(code: str) -> str:
    """Per-type SEO meta description; empty string falls through to the
    generic browse.html template default. Returning empty rather than a
    generic string for unknown codes lets the template's {% if %}
    branch decide the fallback — keeps the source-of-truth in one place
    (this dict) without forcing every weird type code through a
    one-size-fits-all string."""
    return TYPE_META_DESCRIPTIONS.get(code, "")


# Section grouping that mirrors the legacy left nav (`site/partsnav.tmpl`):
# Lower Parts → Upper Parts → Other. List-of-tuples preserves the legacy
# order both for sections and for types within each section.
TYPE_SECTIONS = [
    ("Lower Parts", [
        "strippedlower", "completelower", "upperlower",
        "lpk", "lbk", "trigger", "grip", "stock", "buffer", "mag",
    ]),
    ("Upper Parts", [
        "strippedupper", "completeupper", "bcg", "barrel",
        "muzzle", "ch", "rail", "gasblock", "gastube",
        "sight", "optic",   # AR15Discounts emits "optics" plural; alias
                             # below collapses the count into "optic".
    ]),
    ("Other", ["lprt", "tool", "clean"]),
]


# Scraper-side type-code variations that should resolve to a single
# canonical code in the display layer (sidebar counts, /browse filter
# matching, etc.). Eventually the scrapers and the rows they wrote
# get normalized; until then this map keeps duplicates from showing
# up as separate sidebar rows. See TODO.md "type-code aliases".
TYPE_ALIASES = {
    "optics": "optic",
}


def canonical_type(code: str) -> str:
    """Resolve a scraper-emitted type code to its canonical form."""
    return TYPE_ALIASES.get(code, code)


def aliases_for(canonical: str) -> list:
    """All type codes that should match a canonical filter — the
    canonical itself plus any scraper-side variants that alias to it.
    Used on the read path (queries.in_stock) so /browse?type=optic
    returns BOTH 'optic' and 'optics' rows."""
    return [canonical] + [src for src, tgt in TYPE_ALIASES.items()
                          if tgt == canonical]

# Flat type-code → section-name lookup (used by templates if they need it).
TYPE_TO_SECTION = {
    t: section for section, types in TYPE_SECTIONS for t in types
}


# Sections that ALWAYS render even when empty, as a rifle-anatomy
# "shopping checklist" hint. "Other" intentionally NOT in this set —
# it appears only when there's actual content (tools/cleaning/
# anything-unmapped). Future: use the empty-Other state for
# suggestive selling ("don't forget cleaning supplies or tools",
# link to the categories). See TODO.md.
ALWAYS_SHOW_SECTIONS = {"Lower Parts", "Upper Parts"}


def group_by_section(by_type: dict) -> dict:
    """Re-bucket a {type_code: [lines]} dict into
    {section_name: {type_code: [lines]}} in legacy nav order.

    Sections that appear in ALWAYS_SHOW_SECTIONS (Lower Parts, Upper
    Parts — the rifle anatomy) render even when empty as a placeholder
    cue on /build. Other sections only appear when populated.

    - Sections + types appear in the order defined in TYPE_SECTIONS.
    - Any type not in TYPE_TO_SECTION falls into the 'Other' catch-all
      — which is only added to `out` when something actually lands in it.
    - The '_missing' type (parts no longer in the catalog) gets its
      own trailing 'No longer tracked' section, also content-only.
    """
    # Pre-seed only the always-show sections, in TYPE_SECTIONS order.
    out = {section: {} for section, _ in TYPE_SECTIONS
           if section in ALWAYS_SHOW_SECTIONS}
    for section, types in TYPE_SECTIONS:
        for t in types:
            if t in by_type and by_type[t]:
                out.setdefault(section, {})[t] = by_type[t]
    # Catch types not in our section map → 'Other' (created lazily).
    handled = {t for sec in out.values() for t in sec}
    for t, lines in by_type.items():
        if t == "_missing" or t in handled or not lines:
            continue
        out.setdefault("Other", {})[t] = lines
    if "_missing" in by_type and by_type["_missing"]:
        out["No longer tracked"] = {"_missing": by_type["_missing"]}
    return out
