#!/usr/bin/env python3
"""
MaturityEngine – berechnet stability, dependency_bias, regression_factor
Input: age, bond_duration, conflict_history, loneliness_history
Output: maturity_output.json
"""

import json
import os

PATHS = {
    "config": os.path.expanduser("~/natiris/config/character_genesis.json"),
    "core_state": os.path.expanduser("~/natiris/core/core_state.json"),
    "history": os.path.expanduser("~/natiris/memory/long/history.json"),
    "output": os.path.expanduser("~/natiris/core/maturity_output.json"),
}

def clamp(val, lo=0.0, hi=1.0):
    return max(lo, min(hi, float(val)))

def compute_maturity(config, core, history):
    start_age = config.get("initial_traits", {}).get("mood", 20)
    bond_started = core.get("bond_started_at")

    conflict_history = history.get("conflict_history", [])
    loneliness_history = history.get("loneliness_history", [2])

    age = start_age + (len(conflict_history) * 0.5)
    bond_duration = len([c for c in conflict_history if c]) if bond_started else 0

    conflict_rate = len([c for c in conflict_history if c]) / max(len(conflict_history), 1)
    avg_loneliness = sum(loneliness_history) / max(len(loneliness_history), 1)

    stability_bias = clamp(age / 100 + (bond_duration * 0.01) - (conflict_rate * 0.5))
    dependency_bias = clamp(0.3 + (bond_duration * 0.02) - (avg_loneliness * 0.02))
    regression_factor = clamp(conflict_rate * 0.7 + (1 - age / 100) * 0.5 + (avg_loneliness * 0.05))

    return {
        "stability_bias": round(stability_bias, 3),
        "dependency_bias": round(dependency_bias, 3),
        "regression_factor": round(regression_factor, 3)
    }

def main():
    with open(PATHS["config"]) as f:
        config = json.load(f)
    with open(PATHS["core_state"]) as f:
        core = json.load(f)
    with open(PATHS["history"]) as f:
        history = json.load(f)

    result = compute_maturity(config, core, history)

    with open(PATHS["output"], "w") as f:
        json.dump(result, f, indent=2)

    print(json.dumps(result, indent=2))

if __name__ == "__main__":
    main()
