"""registry.traffic — Canary / weighted traffic routing."""
from __future__ import annotations
import json, random
from typing import Dict, Optional


def resolve_version(agent: Dict, request_headers: Dict = None) -> int:
    """Resolve which version to use based on traffic rules."""
    rules_str = agent.get("traffic_rules")
    if not rules_str:
        return agent["current_version"]
    try:
        rules = json.loads(rules_str) if isinstance(rules_str, str) else rules_str
    except (json.JSONDecodeError, TypeError):
        return agent["current_version"]
    rule_list = rules.get("rules", [])
    if not rule_list:
        return agent["current_version"]
    headers = request_headers or {}
    for rule in rule_list:
        match = rule.get("match", "default")
        if isinstance(match, dict):
            header_key = list(match.keys())[0] if match else None
            if header_key and headers.get(header_key) == match[header_key]:
                return rule["version"]
        elif match == "default":
            continue
    # Weighted random
    total = sum(r.get("weight", 0) for r in rule_list)
    if total <= 0:
        return agent["current_version"]
    r = random.uniform(0, total)
    cumulative = 0
    for rule in rule_list:
        cumulative += rule.get("weight", 0)
        if r <= cumulative:
            return rule["version"]
    return agent["current_version"]
