"""Conditional rule detection and management for form graphs."""

from .graph_builder import _find_page
from .models import ConditionalEffect, ConditionalOperator, ConditionalRule, FormGraph


def detect_conditional(
    graph: FormGraph,
    page_id: str,
    trigger_field_id: str,
    trigger_value: str,
    fields_before: list[str],
    fields_after: list[str],
) -> list[ConditionalRule]:
    """
    Compare visible field_ids before and after toggling a value to detect conditionals.

    Returns a list of ConditionalRules: one with effect="show" for fields that
    appeared, and one with effect="hide" for fields that disappeared. Returns
    an empty list if no changes detected.
    """
    _find_page(graph=graph, page_id=page_id)

    before_set = set(fields_before)
    after_set = set(fields_after)

    appeared = sorted(after_set - before_set)
    disappeared = sorted(before_set - after_set)

    rules: list[ConditionalRule] = []

    if appeared:
        rules.append(
            ConditionalRule(
                rule_id=f"{trigger_field_id}_{trigger_value}_show",
                trigger_field_id=trigger_field_id,
                trigger_value=trigger_value,
                operator=ConditionalOperator.EQUALS,
                affected_field_ids=appeared,
                effect=ConditionalEffect.SHOW,
                verified=False,
            )
        )

    if disappeared:
        rules.append(
            ConditionalRule(
                rule_id=f"{trigger_field_id}_{trigger_value}_hide",
                trigger_field_id=trigger_field_id,
                trigger_value=trigger_value,
                operator=ConditionalOperator.EQUALS,
                affected_field_ids=disappeared,
                effect=ConditionalEffect.HIDE,
                verified=False,
            )
        )

    return rules


def add_conditional(
    graph: FormGraph,
    page_id: str,
    rule: ConditionalRule,
) -> None:
    page = _find_page(graph=graph, page_id=page_id)

    for existing_rule in page.conditionals:
        if existing_rule.rule_id == rule.rule_id:
            msg = f"Conditional rule '{rule.rule_id}' already exists on page '{page_id}'"
            raise ValueError(msg)

    page.conditionals.append(rule)
