"""Lossless, validated edits of Codex's per-session subagent limit (Python 3.11+)."""

import copy
import re
try:
    import tomllib
except ImportError:
    raise SystemExit("Codex settings configuration requires Python 3.11 or newer") from None

KEY = "max_concurrent_threads_per_session"


def limits(document):
    """Report only delegation settings; never expose arbitrary configuration values."""
    agents = document.get("agents", {})
    feature = document.get("features", {}).get("multi_agent_v2")
    override = feature.get(KEY) if isinstance(feature, dict) else None
    configured = agents.get(KEY, agents.get("max_threads"))
    return {"configured": configured, "feature_override": override,
            "effective": override if override is not None else configured}


def validate_overrides(document, value):
    """Reject conflicting feature/profile overrides instead of silently missing the cap."""
    for name, item in [("default", document), *document.get("profiles", {}).items()]:
        if not isinstance(item, dict):
            continue
        current = limits(item)
        if current["feature_override"] not in (None, value):
            raise ValueError(f"{name}: features.multi_agent_v2 overrides the requested subagent limit")
        if name != "default" and current["configured"] not in (None, value):
            raise ValueError(f"{name}: profile overrides the requested subagent limit")


def dotted_pattern(parts):
    return r'\s*\.\s*'.join(r'(?:' + re.escape(part) + r'|"' + re.escape(part)
                            + r'"|\x27' + re.escape(part) + r'\x27)' for part in parts)


def edit_setting(source, table, key, literal, aliases=()):
    """Edit table/dotted assignments, or remove one when literal is None."""
    headers = [re.compile(r'^\s*\[\s*' + dotted_pattern(table[:depth]) + r'\s*\]\s*(?:#.*)?$')
               for depth in range(1, len(table) + 1)]
    assignments = [re.compile(r'^\s*(?:' + '|'.join(dotted_pattern((*table[depth:], name))
                                                 for name in (key, *aliases)) + r')\s*=')
                   for depth in range(len(table) + 1)]
    section, output, inserted = 0, [], False
    for line in source.splitlines(keepends=True):
        if line.lstrip().startswith("["):
            section = next((depth for depth, header in enumerate(headers, 1)
                            if header.match(line.rstrip("\r\n"))), None)
            if section == len(table) and literal is not None and not inserted:
                output.extend([line.rstrip("\r\n") + "\n", f"{key} = {literal}\n"])
                inserted = True
                continue
        if section is not None and assignments[section].match(line):
            if literal is not None and not inserted:
                output.append(f"{'.'.join((*table[section:], key))} = {literal}\n")
                inserted = True
            continue
        output.append(line)
    if literal is not None and not inserted:
        output.extend([f"\n[{'.'.join(table)}]\n", f"{key} = {literal}\n"])
    return "".join(output)


def updated_config(source, value):
    """Set the v2 feature cap and agents fallback, preserving enablement and unrelated values."""
    original = tomllib.loads(source)
    validate_overrides({"profiles": original.get("profiles", {})}, value)
    expected = copy.deepcopy(original)
    agents = expected.setdefault("agents", {})
    agents.pop("max_threads", None)
    agents[KEY] = value
    features = expected.setdefault("features", {})
    feature = features.get("multi_agent_v2")
    result = edit_setting(source, ("agents",), KEY, value, ("max_threads",))
    if isinstance(feature, bool):
        result = edit_setting(result, ("features",), "multi_agent_v2", None)
        result = edit_setting(result, ("features", "multi_agent_v2"), "enabled", str(feature).lower())
        features["multi_agent_v2"] = {"enabled": feature}
    elif feature is None:
        features["multi_agent_v2"] = {}
    features["multi_agent_v2"][KEY] = value
    result = edit_setting(result, ("features", "multi_agent_v2"), KEY, value)
    try:
        unchanged = tomllib.loads(result) == expected
    except tomllib.TOMLDecodeError:
        unchanged = False
    if not unchanged:
        raise ValueError("unsupported Codex TOML layout; use normal [agents] and [features.multi_agent_v2] tables")
    return result
