"""Species icon + spacing registry — VERBATIM port from v1.

Source: /srv/apps/garden/app/main.py lines ~204-374 (SPECIES_ICONS,
DEFAULT_SPECIES_ICON, SPECIES_SPACING_DEFAULTS, species_icon) and
~4150-4158 (species_icon_color). The icon set is kept identical per the
approved plan — do NOT "improve" entries (including the legacy "Brocolli"
typo key, kept alongside the canonical "Broccoli").

For each known species name the registry holds either a unicode emoji
(rendered as plain text) or an SVG symbol id (rendered via <use> against the
species sprite, served at /species-sprite.svg). Anything not in the map falls
back to the leaf symbol.

Emoji are written as \\U escape sequences on purpose (standards: no literal
emoji in committed files).
"""
from __future__ import annotations

import hashlib

# Per-species spacing defaults (plants_per_unit, space_per_unit_sqft).
# `space_per_unit_sqft` is the size of one icon's footprint on the area sketch
# in square feet (so a 2 sqft tomato icon takes up a 2x2 ft visual block);
# `plants_per_unit` is how many actual plants that one icon represents.
# The area-sketch renderer uses these to size icons proportionally and to
# compute icon counts for grouped crops (e.g. 30 carrots -> 10 icons of 3).
SPECIES_SPACING_DEFAULTS = [
    # warm-season anchors
    ("Tomato",            1, 2.0),
    ("Bell Peppers",      1, 1.5),
    ("Hot Pepper",        1, 1.5),
    ("Eggplant",          1, 2.0),
    # brassicas
    ("Cabbage",           1, 2.0),
    ("Cauliflower",       1, 2.0),
    ("Broccoli",          1, 2.0),
    ("Brussels Sprouts",  1, 2.0),
    ("Kale",              1, 1.5),
    # greens / lettuces
    ("Lettuce",           1, 0.5),
    ("Spinach",           2, 0.5),
    # roots
    ("Carrots",           3, 0.5),
    ("Radish",            9, 0.5),
    ("Beet",              4, 0.5),
    ("Onion",             4, 0.5),
    ("Green Onions",      4, 0.5),
    ("Garlic",            4, 0.5),
    ("Potato",            1, 1.5),
    ("Potatoes",          1, 1.5),
    ("Yams",              1, 2.0),
    # legumes
    ("String Beans",      4, 0.5),
    ("Snap Peas",         4, 0.5),
    # cucurbits
    ("Cucumbers",         1, 1.0),
    ("Squash",            1, 4.0),
    ("Zucchini",          1, 4.0),
    ("Cantaloupe",        1, 4.0),
    # corn (block)
    ("Corn",              1, 1.0),
    # berries / shrubs
    ("Strawberry",        1, 1.0),
    ("Blueberry",         1, 16.0),
    ("Raspberry",         1, 3.0),
    ("Currant",           1, 16.0),
    ("Gooseberry",        1, 16.0),
    ("Jostaberry",        1, 16.0),
    ("Haskap",            1, 16.0),
    ("Lingonberry",       1, 4.0),
    ("Blackberry",        1, 16.0),
    ("Marionberry",       1, 16.0),
    ("Tayberry",          1, 16.0),
    ("Loganberry",        1, 16.0),
    ("Branchberry",       1, 16.0),
    ("Pawpaw",            1, 100.0),
    # tree fruits (mature spread)
    ("Apple",             1, 100.0),
    ("Pear",              1, 100.0),
    ("Peach",             1, 100.0),
    ("Plum",              1, 100.0),
    ("Apricot",           1, 100.0),
    ("Cherry",            1, 25.0),
    # vines
    ("Grape",             1, 25.0),
    ("Kiwi",              1, 36.0),
    # herbs
    ("Basil",             1, 1.0),
    ("Parsley",           1, 0.5),
    ("Cilantro",          4, 0.5),
    ("Chives",            1, 1.0),
    # flowers / companions
    ("Marigold",          1, 0.5),
    ("Calendula",         1, 1.0),
    ("Borage",            1, 3.0),
    ("Nasturtium",        1, 1.0),
    ("Alyssum",           1, 0.5),
    ("Creeper",           1, 0.5),
    # cover crops / soil fixers
    ("Buckwheat",         4, 0.5),
    ("White Clover",      16, 0.5),
    ("Comfrey",           1, 9.0),
    # wildlife
    ("Mason Bee",         1, 1.0),
]


SPECIES_ICONS = {
    # Emoji (preferred when one exists)
    "Strawberry": {"type": "emoji", "char": "\U0001F353"},
    "Blueberry": {"type": "emoji", "char": "\U0001FAD0"},
    "Apple": {"type": "emoji", "char": "\U0001F34E"},
    "Pear": {"type": "emoji", "char": "\U0001F350"},
    "Peach": {"type": "emoji", "char": "\U0001F351"},
    "Cherry": {"type": "emoji", "char": "\U0001F352"},
    "Grape": {"type": "emoji", "char": "\U0001F347"},
    "Kiwi": {"type": "emoji", "char": "\U0001F95D"},
    "Tomato": {"type": "emoji", "char": "\U0001F345"},
    "Brocolli": {"type": "emoji", "char": "\U0001F966"},
    "Corn": {"type": "emoji", "char": "\U0001F33D"},
    "Cucumbers": {"type": "emoji", "char": "\U0001F952"},
    "Cabbage": {"type": "emoji", "char": "\U0001F96C"},
    "Eggplant": {"type": "emoji", "char": "\U0001F346"},
    "Bell Peppers": {"type": "emoji", "char": "\U0001FAD1"},
    "Lettuce": {"type": "emoji", "char": "\U0001F96C"},
    "Potatoes": {"type": "emoji", "char": "\U0001F954"},
    "Yams": {"type": "emoji", "char": "\U0001F360"},
    "Green Onions": {"type": "emoji", "char": "\U0001F9C5"},
    "Basil": {"type": "emoji", "char": "\U0001F33F"},
    "Parsley": {"type": "emoji", "char": "\U0001F33F"},
    "Cilantro": {"type": "emoji", "char": "\U0001F33F"},
    "String Beans": {"type": "emoji", "char": "\U0001FAD8"},
    "Snap Peas": {"type": "emoji", "char": "\U0001FADB"},
    "Cantaloupe": {"type": "emoji", "char": "\U0001F348"},
    "Zucchini": {"type": "emoji", "char": "\U0001F952"},
    "Onion": {"type": "emoji", "char": "\U0001F9C5"},
    "Hot Pepper": {"type": "emoji", "char": "\U0001F336"},
    "Carrots": {"type": "emoji", "char": "\U0001F955"},
    "Spinach": {"type": "emoji", "char": "\U0001F96C"},
    "Garlic": {"type": "emoji", "char": "\U0001F9C4"},
    "Marigold": {"type": "emoji", "char": "\U0001F33C"},
    "Buckwheat": {"type": "emoji", "char": "\U0001F33E"},
    "White Clover": {"type": "emoji", "char": "\U0001F340"},

    # New custom SVG symbols (added 2026-05-05) — give species without good
    # emoji their own distinct artwork.
    "Beet":         {"type": "svg", "id": "icon-beet"},
    "Radish":       {"type": "svg", "id": "icon-radish"},
    "Chives":       {"type": "svg", "id": "icon-chives"},
    "Comfrey":      {"type": "svg", "id": "icon-comfrey"},
    "Borage":       {"type": "svg", "id": "icon-borage"},
    "Nasturtium":   {"type": "svg", "id": "icon-nasturtium"},
    "Calendula":    {"type": "svg", "id": "icon-calendula"},
    "Mason Bee":    {"type": "svg", "id": "icon-mason-bee"},
    "Broccoli": {"type": "emoji", "char": "\U0001F966"},  # canonical spelling now
    "Brussels Sprouts": {"type": "emoji", "char": "\U0001F96C"},
    "Kale": {"type": "emoji", "char": "\U0001F33F"},
    "Potato": {"type": "emoji", "char": "\U0001F954"},  # singular vs existing "Potatoes"

    # SVG symbols defined in the species sprite
    "Raspberry": {"type": "svg", "id": "icon-raspberry"},
    "Currant": {"type": "svg", "id": "icon-currant"},
    "Haskap": {"type": "svg", "id": "icon-haskap"},
    "Jostaberry": {"type": "svg", "id": "icon-jostaberry"},
    "Gooseberry": {"type": "svg", "id": "icon-gooseberry"},
    "Lingonberry": {"type": "svg", "id": "icon-lingonberry"},
    "Blackberry": {"type": "svg", "id": "icon-blackberry"},
    "Marionberry": {"type": "svg", "id": "icon-marionberry"},
    "Tayberry": {"type": "svg", "id": "icon-tayberry"},
    "Loganberry": {"type": "svg", "id": "icon-loganberry"},
    "Branchberry": {"type": "svg", "id": "icon-blackberry"},
    "Pawpaw": {"type": "svg", "id": "icon-pawpaw"},
    "Plum": {"type": "svg", "id": "icon-plum"},
    "Apricot": {"type": "svg", "id": "icon-apricot"},
    "Alyssum": {"type": "svg", "id": "icon-alyssum"},
    "Creeper": {"type": "svg", "id": "icon-creeper"},
    "Squash": {"type": "svg", "id": "icon-squash"},
    "Cauliflower": {"type": "svg", "id": "icon-cauliflower"},
}
DEFAULT_SPECIES_ICON = {"type": "svg", "id": "icon-leaf"}


def species_icon(name: str | None) -> dict:
    """Returns {'type': 'emoji'|'svg', 'char'|'id': ...} (v1-identical)."""
    if not name:
        return DEFAULT_SPECIES_ICON
    return SPECIES_ICONS.get(name, DEFAULT_SPECIES_ICON)


def species_icon_color(name) -> str:
    """Stable HSL color from a species name. Used to tint plant icons in the
    area sketch so different species are visually distinguishable."""
    s = (name or "").strip()
    if not s:
        return "hsl(0, 0%, 70%)"
    digest = hashlib.md5(s.lower().encode("utf-8")).hexdigest()
    hue = int(digest[:4], 16) % 360
    return f"hsl({hue}, 55%, 50%)"


def get_icon_descriptor(name: str | None) -> dict:
    """The {icon, color} pair merged into every species/variety payload by
    the catalog service — one call site, one shape."""
    return {"icon": species_icon(name), "color": species_icon_color(name)}


_SPACING_BY_LOWER_NAME: dict[str, tuple[int, float]] = {
    name.lower(): (ppu, sqft) for name, ppu, sqft in SPECIES_SPACING_DEFAULTS
}


def spacing_default_for(name: str | None) -> tuple[int, float] | None:
    """Case-insensitive registry lookup.

    v2 equivalent of v1's idempotent startup seed (main.py ~534-541, which
    upgraded rows still at the (1, 1.0) initial default). Applied at species
    creation time instead: a new species whose name matches the registry and
    whose caller supplied no explicit spacing gets the registry values.
    """
    if not name:
        return None
    return _SPACING_BY_LOWER_NAME.get(name.strip().lower())
