################################################################################
#  REAL RELATIONSHIPS PATCH  (So Much to Love 0.4.4R)
#  Drop this file into game/ - nothing else is needed.
#  Works on a new game, an ongoing one, and the replay gallery.
#
#  How it works:
#  CharacterRoles reads its layers in this order:
#      player override  >  patched update  >  PATCH  >  update  >  base
#  This patch fills ONLY the PATCH layer (store.roles_patched) and never
#  writes to persistent.role_overrides, therefore:
#    - anything the player picks in game always wins over this patch;
#    - every relationship prompt (the questions at the start of a new game,
#      sophie_relations, leana_relations_update, Tiffany, Lisa) comes
#      pre-filled with the family words - pressing OK / "Keep this" is enough.
#
#  Case rules: roles are lowercase (they sit mid-sentence), sweet names are
#  capitalized (they replace a name). sweet = Dad/Mom, sweet1 = Daddy/Mommy.
#
#  entourage -> "family": only the stock default "friend group" (or an
#  empty value) is replaced; a group name typed by the player is kept.
#
#  Two ways to customize:
#    1) in game relationship prompts - that creates overrides,
#       which beat the tables below without editing this file;
#    2) edit the tables below (they are the patch defaults).
#
#  Age editor (4th button in the relationship menu): Alice is the anchor -
#  set her age and every character shifts by the same amount, so relative
#  ages stay story-consistent. Entering 20 restores the story defaults.
#  Hardcoded "X-year-old" phrases in dialogue are re-synced with the live
#  ages automatically.
#
################################################################################
#                                                                                #
#   WARNING - SPOILERS!                                                          #
#   The relationship tables below spell out the real family tree,                #
#   including reveals the story saves for later (e.g. chp1_p2_01).               #
#   If you want to keep the surprises, DO NOT read the tables -                  #
#   just drop the file into game/ and play.                                      #
#                                                                                #
################################################################################

init -10 python:
    # The patch-layer container. Created before every other block so the
    # define below can fill it.
    class _RealRelationshipsContainer(object):
        pass

define roles_patched = _RealRelationshipsContainer()

# Format: roles_patched.X = who X is to the others.
#   role       - X's role towards Y    ("Alice is your daughter")
#   role1      - second role (Leana's story reveal, chp1_p2_01)
#   sweet      - how X addresses Y
#   sweet1/2   - secondary pet names
init 1 python:

    # ---- MC ---------------------------------------------------------------
    roles_patched.mc = CharacterRoles("mc", {
        "ma": {"role": "son",       "sweet": "Mom", "sweet1": "Mommy"},
        "al": {"role": "father"},
        "ha": {"role": "father"},
        "ni": {"role": "brother"},
        "le": {"role": "uncle",     "role1": "father"},
        "so": {"role": "nephew",    "sweet": "Sophie"},
    })

    # ---- Macy ---------------------------------------------------------------
    roles_patched.ma = CharacterRoles("ma", {
        "mc": {"role": "mother"},
        "ni": {"role": "mother"},
        "al": {"role": "grandmother"},
        "ha": {"role": "grandmother"},
        "le": {"role": "grandmother"},
    })

    # ---- Alice ---------------------------------------------------------------
    roles_patched.al = CharacterRoles("al", {
        "mc": {"role": "daughter",  "sweet": "Dad",  "sweet1": "Daddy"},
        "ca": {"role": "daughter",  "sweet": "Mom",  "sweet1": "Mommy"},
        "ha": {"role": "sister"},
        "ma": {"role": "granddaughter"},
    })

    # ---- Hailey ---------------------------------------------------------------
    roles_patched.ha = CharacterRoles("ha", {
        "mc": {"role": "daughter",  "sweet": "Dad",  "sweet1": "Daddy"},
        "ca": {"role": "daughter",  "sweet": "Mom",  "sweet1": "Mommy"},
        "al": {"role": "sister"},
        "ma": {"role": "granddaughter"},
    })

    # ---- Cassey (MC's wife) ---------------------------------------------------
    roles_patched.ca = CharacterRoles("ca", {
        "al": {"role": "mother"},
        "ha": {"role": "mother"},
    })

    # ---- Nicole ---------------------------------------------------------------
    roles_patched.ni = CharacterRoles("ni", {
        "mc": {"role": "sister"},
        "ma": {"role": "daughter",  "sweet": "Mom"},
        "le": {"role": "mother"},
        "so": {"role": "niece",     "sweet": "Sophie"},
    })

    # ---- Leana (role1/sweet1 are re-seeded by the story, chp1_p2_01) -----------
    roles_patched.le = CharacterRoles("le", {
        "mc": {"role": "niece",     "role1": "daughter", "sweet": "Uncle", "sweet1": "Dad"},
        "ni": {"role": "daughter",  "sweet": "Mom"},
        "ma": {"role": "granddaughter"},
    })

    # ---- Sophie ---------------------------------------------------------------
    roles_patched.so = CharacterRoles("so", {
        "ma": {"role": "sister"},
        "mc": {"role": "aunt"},
        "ni": {"role": "aunt"},
    })

    # ---- Neighbours: Eve and Tiffany (mother and daughter) ---------------------
    roles_patched.ev = CharacterRoles("ev", {
        "ti": {"role": "mother"},
    })

    roles_patched.ti = CharacterRoles("ti", {
        "ev": {"role": "daughter",  "sweet": "Mom"},
    })

    # ---- Office: Rebecca and Lisa (mother and daughter) ------------------------
    roles_patched.reb = CharacterRoles("reb", {
        "lis": {"role": "mother"},
    })

    roles_patched.lis = CharacterRoles("lis", {
        "reb": {"role": "daughter", "sweet": "Mom"},
    })

    # Intentionally left to the base game (already correct there):
    #   mc <-> ca = husband / wife, Macy's pet name for MC (his name),
    #   the girls' "Nana" for Macy, doc / jes and the rest of the minor cast.

################################################################################
#  entourage -> "family"
#  Runs after every default application (new game, replay, rollback), after
#  a save load, and once at init. Replaces only the stock default
#  "friend group" (or an empty value); a group name typed by the player
#  is left untouched.
################################################################################

init 1 python:
    def _rrp_apply_entourage():
        if getattr(store, "entourage", None) in (None, "", "friend group"):
            store.entourage = "family"

    _rrp_apply_entourage()

    for _rrp_cb_list_name in ("after_default_callbacks", "after_load_callbacks"):
        _rrp_cb_list = getattr(config, _rrp_cb_list_name, None)
        if _rrp_cb_list is not None and (_rrp_apply_entourage not in _rrp_cb_list):
            _rrp_cb_list.append(_rrp_apply_entourage)

################################################################################
#  Character ages
#  Alice is the anchor: pick her age and every other character shifts by the
#  same amount, so all relative ages (family and non-family) stay consistent
#  with the story. Entering 20 - the story default - resets everyone.
#
#  rrp_base_ages must mirror the age= values in
#  Scripts/CharacterData/Characters.rpy (re-check after game updates).
################################################################################

define rrp_base_ages = {
    "mc": 44, "ma": 65, "so": 65, "al": 20, "ha": 18, "ca": 40,
    "ni": 40, "le": 18, "ti": 18, "ev": 40, "reb": 36, "lis": 19,
    "jes": 30, "doc": 34,
}

init 1 python:
    def rrp_edit_ages():
        """Ask for Alice's age and shift every character by the same amount.
        Returns the applied shift (0 when the story defaults are kept)."""
        anchor = "al"
        base = rrp_base_ages
        # keep the oldest characters (Macy / Sophie: +45) under 100
        max_allowed = 99 - max(base[t] - base[anchor] for t in base)

        raw = DynamicIntInput(
            "Character ages - all other ages are recalculated automatically to keep the story consistent",
            "How old is [al]? Enter {b}20{/b} to restore the story defaults.",
            str(base[anchor]),
            "Alice is xxx years old.",
            min_value=3,
            max_value=max_allowed,
        )

        try:
            new_age = int(float(raw))
        except (TypeError, ValueError):
            return 0

        shift = new_age - base[anchor]
        if shift == 0:
            return 0

        for tag, base_age in base.items():
            obj = getattr(stats, tag, None)
            if obj is not None:
                obj.age = base_age + shift
                # keep the flashback variant consistent too (MC only)
                if hasattr(obj, "yngAge"):
                    obj.yngAge = obj.yngAge + shift
        return shift

################################################################################
#  "Reset them to the patch defaults." button in the relationship menu.
#
#  config.label_overrides is applied by the engine to every jump/call made
#  by name, so:
#    "start"        -> rrp_start_here    (the game's start_here: name prompts,
#                                         then the relationship menu)
#    "restart_menu" -> rrp_restart_menu  (the relationship menu + the Reset
#                                         button; every "Start over from the
#                                         beginning." lands here too)
################################################################################

define config.label_overrides = {
    "start": "rrp_start_here",
    "restart_menu": "rrp_restart_menu",
}

label rrp_start_here:
    # mirrors the game's start_here - re-check against it after game updates
    $ print_version_string()

    stop music fadeout 1.0
    scene black with fade

    $ persistent.name = DynamicInput("You are choosing the name of the main character:",
                                        "What is his first name?",
                                        persistent.name,
                                        "Hello, I am xxx.")

    $ persistent.sname = DynamicInput("You are choosing the name of the main character:",
                                        "What is his surname?",
                                        persistent.sname,
                                        f"Hello, I am {persistent.name} xxx.")

    jump rrp_restart_menu

label rrp_restart_menu:
    scene black
    show relationship_text_displayable

    menu:
        "Change them.":
            jump relations

        "Keep them.":
            $ ha_relations = True
            jump end_relations


        "Reset them to the patch defaults.":
            # Clears ALL manual overrides (persistent.role_overrides), so the
            # patch-layer values take over: later edits of the tables above
            # apply without re-typing anything.
            # Then: "Change them." re-fills the prompts with the patched
            # values, "Keep them." continues on the patch defaults.
            $ CharacterRoles.clear_all_overrides()
            $ renpy.notify('Relationships reset to patch defaults. Use "Change them." to customize, or continue.')
            jump rrp_restart_menu

        "Edit ages.":
            $ rrp_age_shift = rrp_edit_ages()
            if rrp_age_shift != 0:
                "Ages updated (shift: [rrp_age_shift]): [persistent.name] is [stats.mc.age], [ma] is [stats.ma.age], [so] is [stats.so.age], [ca] is [stats.ca.age], [ni] is [stats.ni.age], [al] is [stats.al.age], [ha] is [stats.ha.age], [le] is [stats.le.age], [ev] is [stats.ev.age], [ti] is [stats.ti.age], [reb] is [stats.reb.age], [lis] is [stats.lis.age], [jes] is [stats.jes.age], [doc] is [stats.doc.age]."
            jump rrp_restart_menu
################################################################################
#  Hardcoded ages in dialogue
#  Lines like "my 20-year-old [roles.al.role.mc]" keep a literal age while the
#  real value lives in stats. This filter replaces the number with the live
#  stats.<tag>.age whenever a "N-year-old" is directly followed by a
#  [roles.<tag>...] or [stats.<tag>...] variable.
#  Past-tense mentions without a variable (e.g. "a 50-year-old woman" in
#  chp1_p2_05) are left alone on purpose: they describe an age from the
#  story's past, not the current one.
################################################################################

init 1 python:
    import re

    _rrp_hardcoded_age = re.compile(r"(\d+)-year-old(\s+\[(?:roles|stats)\.([a-z]+)\.[^\]]+\])")

    def _rrp_fix_hardcoded_ages(text):
        def _sub(match):
            tag = match.group(3)
            obj = getattr(stats, tag, None)
            if obj is None or not hasattr(obj, "age"):
                return match.group(0)
            return "{0}-year-old{1}".format(obj.age, match.group(2))
        return _rrp_hardcoded_age.sub(_sub, text)

    _rrp_prev_say_filter = getattr(config, "say_menu_text_filter", None)

    def _rrp_say_menu_filter(text):
        if _rrp_prev_say_filter is not None:
            try:
                text = _rrp_prev_say_filter(text)
            except Exception:
                pass
        try:
            text = _rrp_fix_hardcoded_ages(text)
        except Exception:
            pass
        return text

    config.say_menu_text_filter = _rrp_say_menu_filter
