import yaml

with open("correlation/rules.yaml") as f:
    RULES = yaml.safe_load(f)

def correlate(alert):
    service = alert["service"]
    rules = RULES["services"].get(service, {})
    return {
        "service": service,
        "severity": alert["severity"],
        "metrics": alert["metrics"],
        "depends_on": rules.get("depends_on", []),
        "impact": rules.get("impact", [])
    }

def evaluate(rules: list, metrics: dict):
    incidents = []

    for rule in rules:
        matched = True

        for metric, condition in rule["when"].items():
            value = metrics.get(metric)

            if value is None:
                matched = False
                break

            if "gt" in condition and value <= condition["gt"]:
                matched = False

            if "lt" in condition and value >= condition["lt"]:
                matched = False

        if matched:
            incidents.append({
                "id": rule["id"],
                "severity": rule["severity"],
                "impact": rule["impact"],
                "metrics": metrics,
            })

    return incidents
