#!/usr/bin/env python3
"""Brand loader — reads the bundled brand.json so the engine surface is data-driven.

A brand build (build_brand.sh) emits brand.json into the .app's Resources from its
TOML manifest; a direct PageHawk build writes a default one. The Swift shell and the
Python engine both consult it to mount only enabled modules and open to the right
default view, so one core serves many brands without forking (see ../../BRANDS.md).

Lookup order for brand.json:
  1) $WINNOW_BRAND_JSON / $BRAND_JSON  (explicit override, e.g. dev/testing)
  2) <this dir>/../brand.json          (bundled: Resources/engine/.. = Resources)
  3) <repo>/brands/<name>.json or the repo default
Falls back to the full-featured PageHawk default if none is found (never raises)."""
import os, json, functools

_HERE = os.path.dirname(os.path.abspath(__file__))

_DEFAULT = {
    "brand": "pagehawk", "name": "PageHawk", "open_to": "grid",
    "modules": {"sort": True, "read": True, "compare": True, "ai": True,
                "sync": True, "redact": True, "dataroom": True, "dedupe": True,
                "quality_score": False, "raw_decode": False},
}


def _candidates():
    env = os.environ.get("WINNOW_BRAND_JSON") or os.environ.get("BRAND_JSON")
    if env:
        yield env
    # bundled: Resources/engine/brand.py -> Resources/brand.json
    yield os.path.join(os.path.dirname(_HERE), "brand.json")
    # dev: alongside this file, or repo root
    yield os.path.join(_HERE, "brand.json")
    yield os.path.join(_HERE, "..", "..", "brand.json")


@functools.lru_cache(maxsize=1)
def brand():
    """The resolved brand dict (cached). Always returns a dict; never raises."""
    for p in _candidates():
        try:
            if p and os.path.isfile(p):
                d = json.load(open(p))
                if isinstance(d, dict) and d.get("modules"):
                    out = dict(_DEFAULT)
                    out.update(d)
                    return out
        except Exception:
            continue
    return dict(_DEFAULT)


def module_on(name):
    """Is a build-time module enabled for this brand?"""
    return bool(brand().get("modules", {}).get(name, False))


def default_view():
    """Which view the app opens to (e.g. 'grid' or 'sort')."""
    return brand().get("open_to", "grid")


def is_winnow():
    """True when this build is the photo specialist (its photo deltas are mounted)."""
    return module_on("dedupe") and module_on("quality_score")


def name():
    return brand().get("name", "PageHawk")


if __name__ == "__main__":
    import sys
    b = brand()
    print(json.dumps({"name": b.get("name"), "brand": b.get("brand"),
                      "open_to": default_view(), "is_winnow": is_winnow(),
                      "modules_on": [k for k, v in b.get("modules", {}).items() if v]},
                     indent=2))
    sys.exit(0)
