from __future__ import annotations

from collections import deque
from copy import deepcopy
from dataclasses import dataclass, field
import re
from typing import Any, Callable


SUPPORTED_NODE_TYPES = {
    "start",
    "message",
    "buttons",
    "question",
    "condition",
    "save_variable",
    "go_to_journey",
    "action",
    "product_finder",
    "end",
}

SUPPORTED_ACTIONS = {"woocommerce.get_order"}

OPERATORS = {
    "equals",
    "not_equals",
    "greater_than",
    "greater_or_equal",
    "less_than",
    "less_or_equal",
    "contains",
    "exists",
}


class JourneyValidationError(ValueError):
    def __init__(self, errors: list[dict[str, str]], warnings: list[dict[str, str]] | None = None):
        self.errors = errors
        self.warnings = warnings or []
        super().__init__("Journey definition is invalid")


class RuntimeJourneyError(ValueError):
    pass


def _error(code: str, message: str, node_id: str = "") -> dict[str, str]:
    item = {"code": code, "message": message}
    if node_id:
        item["node_id"] = node_id
    return item


def outgoing_references(node: dict[str, Any]) -> list[str]:
    refs: list[str] = []
    node_type = node.get("type")
    if node_type in {"start", "message", "question", "save_variable"} and node.get("next"):
        refs.append(str(node["next"]))
    elif node_type == "buttons":
        refs.extend(str(option["next"]) for option in node.get("options", []) if option.get("next"))
    elif node_type == "condition":
        refs.extend(str(rule["next"]) for rule in node.get("rules", []) if rule.get("next"))
        if node.get("else"):
            refs.append(str(node["else"]))
    elif node_type == "go_to_journey" and node.get("next"):
        refs.append(str(node["next"]))
    elif node_type in {"action", "product_finder"}:
        if node.get("on_success"):
            refs.append(str(node["on_success"]))
        if node_type == "product_finder" and node.get("on_empty"):
            refs.append(str(node["on_empty"]))
        if node.get("on_error"):
            refs.append(str(node["on_error"]))
    return refs


def validate_journey(payload: dict[str, Any], strict: bool = True) -> dict[str, Any]:
    data = deepcopy(payload)
    errors: list[dict[str, str]] = []
    warnings: list[dict[str, str]] = []

    if data.get("schema_version") != "1.0":
        errors.append(_error("unsupported_schema", "schema_version باید 1.0 باشد."))

    journey = data.get("journey")
    if not isinstance(journey, dict):
        errors.append(_error("missing_journey", "بخش journey وجود ندارد."))
        journey = {}

    for field in ("key", "name", "start"):
        if not str(journey.get(field, "")).strip():
            errors.append(_error("missing_field", f"journey.{field} الزامی است."))

    nodes = data.get("nodes")
    if not isinstance(nodes, list) or not nodes:
        errors.append(_error("missing_nodes", "Journey باید حداقل یک Node داشته باشد."))
        nodes = []

    ids: list[str] = []
    node_map: dict[str, dict[str, Any]] = {}
    for index, raw_node in enumerate(nodes):
        if not isinstance(raw_node, dict):
            errors.append(_error("invalid_node", f"Node شماره {index + 1} معتبر نیست."))
            continue
        node_id = str(raw_node.get("id", "")).strip()
        if not node_id:
            errors.append(_error("missing_node_id", f"Node شماره {index + 1} شناسه ندارد."))
            continue
        if node_id in node_map:
            errors.append(_error("duplicate_node_id", f"شناسه {node_id} تکراری است.", node_id))
            continue
        node_type = raw_node.get("type")
        if node_type not in SUPPORTED_NODE_TYPES:
            errors.append(_error("unsupported_node_type", f"نوع Node ناشناخته است: {node_type}", node_id))
        ids.append(node_id)
        node_map[node_id] = raw_node

        if node_type in {"message", "buttons", "question"} and not str(raw_node.get("text", "")).strip():
            errors.append(_error("missing_text", "متن این Node خالی است.", node_id))
        if node_type in {"start", "message", "question", "save_variable"} and not raw_node.get("next"):
            errors.append(_error("missing_next", "مسیر خروجی این Node مشخص نشده است.", node_id))
        if node_type == "buttons":
            options = raw_node.get("options")
            if not isinstance(options, list) or len(options) < 1:
                errors.append(_error("missing_options", "Buttons حداقل به یک گزینه نیاز دارد.", node_id))
            else:
                values: set[str] = set()
                for option in options:
                    if not isinstance(option, dict) or not str(option.get("label", "")).strip():
                        errors.append(_error("invalid_option", "عنوان یکی از گزینه‌ها خالی است.", node_id))
                        continue
                    if not option.get("next"):
                        errors.append(_error("missing_option_next", "مقصد یکی از گزینه‌ها مشخص نشده است.", node_id))
                    value_key = str(option.get("value", ""))
                    if value_key in values:
                        errors.append(_error("duplicate_option", f"مقدار گزینه {value_key} تکراری است.", node_id))
                    values.add(value_key)
        if node_type == "condition":
            rules = raw_node.get("rules")
            if not isinstance(rules, list) or not rules:
                errors.append(_error("missing_rules", "Condition حداقل به یک Rule نیاز دارد.", node_id))
            for rule in rules or []:
                clause = rule.get("if", {}) if isinstance(rule, dict) else {}
                operator = clause.get("operator") if isinstance(clause, dict) else None
                if operator and operator not in OPERATORS:
                    errors.append(_error("invalid_operator", f"عملگر {operator} پشتیبانی نمی‌شود.", node_id))
                if isinstance(rule, dict) and not rule.get("next"):
                    errors.append(_error("missing_rule_next", "مقصد یکی از Ruleها مشخص نشده است.", node_id))
            if not raw_node.get("else"):
                errors.append(_error("missing_else", "مسیر Else برای Condition مشخص نشده است.", node_id))
        if node_type == "save_variable" and not str(raw_node.get("variable", "")).strip():
            errors.append(_error("missing_variable", "نام متغیر برای Save Variable الزامی است.", node_id))
        if node_type == "go_to_journey" and not str(raw_node.get("journey", "")).strip():
            errors.append(_error("missing_target_journey", "Journey مقصد مشخص نشده است.", node_id))
        if node_type == "go_to_journey" and not raw_node.get("next"):
            errors.append(_error("missing_next", "مسیر بازگشت از Sub-Journey مشخص نشده است.", node_id))
        if node_type == "action":
            action = str(raw_node.get("action", "")).strip()
            if action not in SUPPORTED_ACTIONS:
                errors.append(_error("unsupported_action", f"Action مجاز نیست: {action or 'خالی'}", node_id))
            inputs = raw_node.get("input")
            if not isinstance(inputs, dict):
                errors.append(_error("invalid_action_input", "ورودی Action باید یک Object باشد.", node_id))
            elif action == "woocommerce.get_order":
                for input_name in ("order_id", "phone"):
                    if input_name not in inputs:
                        errors.append(_error("missing_action_input", f"ورودی {input_name} الزامی است.", node_id))
            if not str(raw_node.get("save_result", "")).strip():
                errors.append(_error("missing_action_result", "نام متغیر نتیجه Action الزامی است.", node_id))
            if not raw_node.get("on_success"):
                errors.append(_error("missing_action_success", "مسیر موفق Action مشخص نشده است.", node_id))
            if not raw_node.get("on_error"):
                errors.append(_error("missing_action_error", "مسیر خطای Action مشخص نشده است.", node_id))
        if node_type == "product_finder":
            filters = raw_node.get("filters")
            allowed = {"category", "tag", "brand", "taste", "weight", "price_min", "price_max", "q", "orderby", "order"}
            if not isinstance(filters, dict) or any(key not in allowed or not isinstance(value, (str, int, float)) or isinstance(value, bool) for key, value in filters.items()):
                errors.append(_error("invalid_product_filters", "فیلترهای Product Finder معتبر نیستند.", node_id))
            elif any(len(str(value)) > 160 for value in filters.values()):
                errors.append(_error("invalid_product_filters", "مقدار فیلتر بیش از حد مجاز است.", node_id))
            if not str(raw_node.get("save_result", "")).strip():
                errors.append(_error("missing_action_result", "نام متغیر نتیجه الزامی است.", node_id))
            for branch in ("on_success", "on_empty", "on_error"):
                if not raw_node.get(branch):
                    errors.append(_error("missing_product_branch", f"مسیر {branch} باید مشخص شود.", node_id))

    start = str(journey.get("start", ""))
    if start and start not in node_map:
        errors.append(_error("missing_start_node", f"Node شروع با شناسه {start} وجود ندارد."))

    for node_id, node in node_map.items():
        for ref in outgoing_references(node):
            if ref not in node_map:
                errors.append(_error("missing_reference", f"اتصال به Node ناموجود {ref} اشاره می‌کند.", node_id))

    if start in node_map:
        reachable: set[str] = set()
        queue: deque[str] = deque([start])
        while queue:
            current = queue.popleft()
            if current in reachable or current not in node_map:
                continue
            reachable.add(current)
            queue.extend(outgoing_references(node_map[current]))
        for node_id in ids:
            if node_id not in reachable:
                warnings.append(_error("unreachable_node", "این Node از مسیر شروع قابل دسترسی نیست.", node_id))

    if nodes and not any(node.get("type") == "end" for node in nodes if isinstance(node, dict)):
        warnings.append(_error("missing_end", "Journey هیچ End Node ندارد."))

    variables = data.get("variables", {})
    if variables is None:
        data["variables"] = {}
    elif not isinstance(variables, dict):
        errors.append(_error("invalid_variables", "variables باید یک Object باشد."))

    layout = data.get("layout", {})
    if layout is None:
        data["layout"] = {}
    elif not isinstance(layout, dict):
        errors.append(_error("invalid_layout", "layout باید یک Object باشد."))

    result = {
        "valid": not errors,
        "errors": errors,
        "warnings": warnings,
        "summary": {
            "nodes": len(node_map),
            "connections": sum(len(outgoing_references(node)) for node in node_map.values()),
            "variables": len(data.get("variables", {})) if isinstance(data.get("variables"), dict) else 0,
            "sub_journeys": sum(1 for node in node_map.values() if node.get("type") == "go_to_journey"),
        },
        "normalized": data,
    }
    if strict and errors:
        raise JourneyValidationError(errors, warnings)
    return result


TEMPLATE_PATTERN = re.compile(r"{{\s*([A-Za-z0-9_.-]+)\s*}}")


def resolve_variable(path: str, variables: dict[str, Any]) -> Any:
    current: Any = variables
    for part in path.split("."):
        if not isinstance(current, dict) or part not in current:
            return None
        current = current[part]
    return current


def render_template(value: Any, variables: dict[str, Any]) -> Any:
    if isinstance(value, dict):
        return {key: render_template(item, variables) for key, item in value.items()}
    if isinstance(value, list):
        return [render_template(item, variables) for item in value]
    if not isinstance(value, str):
        return value
    full_match = TEMPLATE_PATTERN.fullmatch(value)
    if full_match:
        replacement = resolve_variable(full_match.group(1), variables)
        return value if replacement is None else deepcopy(replacement)

    def replace(match: re.Match[str]) -> str:
        replacement = resolve_variable(match.group(1), variables)
        return match.group(0) if replacement is None else str(replacement)

    return TEMPLATE_PATTERN.sub(replace, value)


def evaluate_clause(clause: dict[str, Any], variables: dict[str, Any]) -> bool:
    if "all" in clause:
        return all(evaluate_clause(item, variables) for item in clause.get("all", []))
    if "any" in clause:
        return any(evaluate_clause(item, variables) for item in clause.get("any", []))
    variable = str(clause.get("variable", ""))
    operator = clause.get("operator", "equals")
    expected = clause.get("value")
    actual = variables.get(variable)
    try:
        if operator == "equals":
            return actual == expected
        if operator == "not_equals":
            return actual != expected
        if operator == "greater_than":
            return float(actual) > float(expected)
        if operator == "greater_or_equal":
            return float(actual) >= float(expected)
        if operator == "less_than":
            return float(actual) < float(expected)
        if operator == "less_or_equal":
            return float(actual) <= float(expected)
        if operator == "contains":
            return expected in actual
        if operator == "exists":
            return variable in variables and actual not in (None, "")
    except (TypeError, ValueError):
        return False
    return False


@dataclass
class RuntimeResult:
    status: str
    node_id: str | None
    messages: list[dict[str, Any]]
    prompt: dict[str, Any] | None
    variables: dict[str, Any]
    journey_key: str
    version: int
    stack: list[dict[str, Any]]
    actions: list[dict[str, Any]] = field(default_factory=list)


def run_until_input(
    definition: dict[str, Any],
    current_node: str,
    variables: dict[str, Any],
    stack: list[dict[str, Any]],
    journey_key: str,
    version: int,
    answer: Any = None,
    load_journey: Callable[[str, int | None], tuple[dict[str, Any], int]] | None = None,
    max_steps: int = 100,
    execute_action: Callable[[str, dict[str, Any]], dict[str, Any]] | None = None,
) -> RuntimeResult:
    messages: list[dict[str, Any]] = []
    answer_pending = answer
    active_definition = definition
    active_key = journey_key
    active_version = version
    action_events: list[dict[str, Any]] = []

    for _ in range(max_steps):
        nodes = {node["id"]: node for node in active_definition.get("nodes", [])}
        node = nodes.get(current_node)
        if node is None:
            raise RuntimeJourneyError(f"Node پیدا نشد: {current_node}")
        node_type = node.get("type")

        if node_type == "start":
            current_node = node.get("next")
        elif node_type == "message":
            messages.append({"type": "message", "text": render_template(node.get("text", ""), variables)})
            current_node = node.get("next")
        elif node_type == "save_variable":
            variables[str(node.get("variable"))] = render_template(node.get("value"), variables)
            current_node = node.get("next")
        elif node_type == "condition":
            current_node = node.get("else")
            for rule in node.get("rules", []):
                if evaluate_clause(rule.get("if", {}), variables):
                    current_node = rule.get("next")
                    break
        elif node_type == "buttons":
            if answer_pending is None:
                return RuntimeResult(
                    "waiting_input",
                    current_node,
                    messages,
                    {
                        "type": "buttons",
                        "text": render_template(node.get("text", ""), variables),
                        "options": [
                            {"label": option.get("label"), "value": option.get("value")}
                            for option in node.get("options", [])
                        ],
                    },
                    variables,
                    active_key,
                    active_version,
                    stack,
                    action_events,
                )
            selected = next(
                (
                    option
                    for option in node.get("options", [])
                    if option.get("value") == answer_pending or option.get("label") == answer_pending
                ),
                None,
            )
            if selected is None:
                raise RuntimeJourneyError("گزینه انتخاب‌شده معتبر نیست.")
            if node.get("save_to"):
                variables[str(node["save_to"])] = selected.get("value")
            current_node = selected.get("next")
            answer_pending = None
        elif node_type == "question":
            if answer_pending is None:
                return RuntimeResult(
                    "waiting_input",
                    current_node,
                    messages,
                    {
                        "type": "question",
                        "text": render_template(node.get("text", ""), variables),
                        "input_type": node.get("input_type", "text"),
                        "placeholder": node.get("placeholder", ""),
                    },
                    variables,
                    active_key,
                    active_version,
                    stack,
                    action_events,
                )
            input_type = node.get("input_type", "text")
            if input_type == "number":
                try:
                    answer_pending = float(answer_pending)
                except (TypeError, ValueError) as exc:
                    raise RuntimeJourneyError("لطفاً یک عدد معتبر وارد کنید.") from exc
            if node.get("save_to"):
                variables[str(node["save_to"])] = answer_pending
            current_node = node.get("next")
            answer_pending = None
        elif node_type == "go_to_journey":
            if load_journey is None:
                raise RuntimeJourneyError("Sub-Journey loader تنظیم نشده است.")
            target = str(node.get("journey", ""))
            target_definition, target_version = load_journey(target, None)
            stack.append(
                {
                    "journey_key": active_key,
                    "version": active_version,
                    "return_to": node.get("next"),
                }
            )
            active_definition = target_definition
            active_key = target
            active_version = target_version
            current_node = str(target_definition["journey"]["start"])
        elif node_type == "action":
            if execute_action is None:
                raise RuntimeJourneyError("Action executor تنظیم نشده است.")
            action_name = str(node.get("action", ""))
            rendered_input = render_template(node.get("input", {}), variables)
            if not isinstance(rendered_input, dict):
                raise RuntimeJourneyError("ورودی Action معتبر نیست.")
            outcome = execute_action(action_name, rendered_input)
            if not isinstance(outcome, dict) or not isinstance(outcome.get("ok"), bool):
                raise RuntimeJourneyError("پاسخ Action معتبر نیست.")
            result_variable = str(node.get("save_result", "action_result"))
            if outcome["ok"]:
                variables[result_variable] = outcome.get("data", {})
                variables.pop(result_variable + "_error", None)
                current_node = node.get("on_success")
                action_events.append({"node_id": node.get("id"), "action": action_name, "ok": True})
            else:
                error = outcome.get("error") if isinstance(outcome.get("error"), dict) else {}
                variables[result_variable] = {}
                variables[result_variable + "_error"] = {
                    "code": str(error.get("code", "action_failed")),
                    "message": str(error.get("message", "Action انجام نشد.")),
                }
                current_node = node.get("on_error")
                action_events.append(
                    {
                        "node_id": node.get("id"),
                        "action": action_name,
                        "ok": False,
                        "error_code": variables[result_variable + "_error"]["code"],
                    }
                )
        elif node_type == "product_finder":
            if execute_action is None:
                raise RuntimeJourneyError("Product Finder executor تنظیم نشده است.")
            filters = render_template(node.get("filters", {}), variables)
            if not isinstance(filters, dict):
                raise RuntimeJourneyError("فیلترهای محصول معتبر نیستند.")
            outcome = execute_action("catalog.search_products", filters)
            if not isinstance(outcome, dict) or not isinstance(outcome.get("ok"), bool):
                raise RuntimeJourneyError("پاسخ جست‌وجوی محصول معتبر نیست.")
            result_variable = str(node.get("save_result", "products"))
            if outcome["ok"]:
                data = outcome.get("data", {})
                if not isinstance(data, dict) or not isinstance(data.get("products"), list):
                    raise RuntimeJourneyError("پاسخ جست‌وجوی محصول معتبر نیست.")
                variables[result_variable] = data
                variables.pop(result_variable + "_error", None)
                if data["products"]:
                    messages.append({"type": "products", "text": render_template(node.get("text", "این محصولات موجود را ببینید:"), variables),
                                     "products": data["products"][:4]})
                    current_node = node.get("on_success")
                else:
                    current_node = node.get("on_empty")
            else:
                error = outcome.get("error") if isinstance(outcome.get("error"), dict) else {}
                variables[result_variable] = {"count": 0, "products": []}
                variables[result_variable + "_error"] = {
                    "code": str(error.get("code", "catalog_failed")),
                    "message": str(error.get("message", "دریافت محصولات انجام نشد.")),
                }
                current_node = node.get("on_error")
            action_events.append({"node_id": node.get("id"), "action": "catalog.search_products",
                                  "ok": bool(outcome["ok"]), "count": len(variables[result_variable].get("products", []))})
        elif node_type == "end":
            if stack:
                parent = stack.pop()
                if load_journey is None:
                    raise RuntimeJourneyError("Sub-Journey loader تنظیم نشده است.")
                active_definition, active_version = load_journey(
                    str(parent["journey_key"]), int(parent["version"])
                )
                active_key = str(parent["journey_key"])
                current_node = parent.get("return_to")
                if not current_node:
                    return RuntimeResult(
                        "completed", None, messages, None, variables, active_key, active_version, stack, action_events
                    )
            else:
                return RuntimeResult(
                    "completed", None, messages, None, variables, active_key, active_version, stack, action_events
                )
        else:
            raise RuntimeJourneyError(f"نوع Node در Runtime پشتیبانی نمی‌شود: {node_type}")

        if not current_node:
            raise RuntimeJourneyError(f"خروجی Node {node.get('id')} مشخص نشده است.")

    raise RuntimeJourneyError("Journey بیش از حد مجاز مرحله اجرا کرد؛ احتمال Loop وجود دارد.")
