from dataclasses import dataclass
from datetime import date
from typing import Callable, Awaitable, Optional, Any
import inspect
import logging

from langgraph.types import StreamWriter
from schema.agent import HRState
from services import slot_store
from services.ai_service import (
    _call_llm,
    _extract_text,
    _safe_json_parse,
    _normalize_usage,
    INTENT_MODEL,
)

logger = logging.getLogger(__name__)


@dataclass
class SlotFlowConfig:
    name: str
    required_fields: list[str]
    field_labels: dict[str, str]
    build_prompt: Callable[[str, dict, date], str]
    submit: Callable[..., Awaitable[dict]]

    format_summary: Optional[Callable[[dict], str]] = None
    format_success: Optional[Callable[[dict, dict], str]] = None

    enrich_slots: Optional[Callable[..., Awaitable[dict]]] = None
    extract_failure_message: Optional[Callable[[dict, dict], Any]] = None
    map_submit_exception: Optional[Callable[[Exception], Optional[str]]] = None
    llm_max_tokens: int = 250

    entry_fields: Optional[list[str]] = None
    entry_field_labels: Optional[dict[str, str]] = None
    entry_key: str = "date"
    format_multi_summary: Optional[Callable[[list[dict]], str]] = None
    format_multi_success: Optional[Callable[[list[dict], list[dict]], str]] = None

    is_explicit_cancel: Optional[Callable[[str], bool]] = None

    # NEW — called once per merged entry that still has a missing field,
    # AFTER this turn's parse+merge. Signature:
    #   async def fn(entry: dict, writer: StreamWriter) -> dict
    # Return value is merged into the entry for any field it doesn't
    # already have.
    fetch_entry_prefill: Optional[Callable[[dict, StreamWriter], Awaitable[dict]]] = None


def _missing_fields_message(
    config: SlotFlowConfig,
    missing: list[str],
) -> str:

    label = config.name.replace("_", " ")

    phrases = [
        config.field_labels[f]
        for f in missing
    ]

    if len(phrases) == 1:
        return (
            f"I still need {phrases[0]} "
            f"to submit your {label} request."
        )

    return (
        "I still need "
        + ", ".join(phrases[:-1])
        + f", and {phrases[-1]} "
        f"to submit your {label} request."
    )


def _guard_cancel_action(config: SlotFlowConfig, action: str, query: str, parsed: dict) -> str:
    """Returns the (possibly corrected) action. If the LLM classified the
    message as "cancel" but the flow has a is_explicit_cancel check and
    the raw message doesn't actually contain cancel language, downgrade
    to "provide_info" with no new entries instead of discarding the
    in-progress request."""
    if action != "cancel":
        return action

    if config.is_explicit_cancel is None:
        return action

    if config.is_explicit_cancel(query):
        return action

    logger.info(
        f"[Graph] {config.name}: overriding LLM cancel guess for "
        f"low-signal message {query!r} -> provide_info"
    )
    parsed["entries"] = parsed.get("entries") or []
    parsed["action"] = "provide_info"
    return "provide_info"


async def run_slot_flow(config, state, writer, prefill_slots=None, candidate_dates=None):
    if config.entry_fields:
        if not (config.format_multi_summary and config.format_multi_success):
            raise ValueError(
                f"[{config.name}] entry_fields is set but "
                f"format_multi_summary/format_multi_success are missing."
            )

        return await _run_multi_entry_flow(
            config, state, writer,
            candidate_dates=candidate_dates,
        )
    if not (config.format_summary and config.format_success):
        raise ValueError(
            f"[{config.name}] single-entry flow requires "
            f"format_summary/format_success."
        )
    query = state["query"]
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    usage_events = list(state.get("usage_events", []))
    label = config.name.replace("_", " ")

    def _finish(
        message: str,
        intent: Optional[str] = None,
        extra_data: Optional[dict] = None
    ) -> dict:
        data = {"answer": message}
        if extra_data:
            data.update(extra_data)

        writer({
            "type": "done",
            "intent": intent or config.name,
            "is_hr": True,
            "data": data,
            "message": message,
            "usage_events": usage_events,
        })

        return {
            "response_text": message,
            "usage_events": usage_events,
        }

    today = date.today()

    existing_slots = slot_store.get_slots(
        config.name,
        company_id,
        conversation_id,
    ) or {}

    if prefill_slots:
        for key, value in prefill_slots.items():
            if value and not existing_slots.get(key):
                existing_slots[key] = value

    if prefill_slots:
        slot_store.set_slots(
            config.name,
            company_id,
            conversation_id,
            existing_slots,
        )

    try:
        prompt = config.build_prompt(
            query,
            existing_slots,
            today,
        )

        raw = await _call_llm(
            prompt,
            max_tokens=config.llm_max_tokens,
            model=INTENT_MODEL,
        )

        parsed = _safe_json_parse(
            _extract_text(raw)
        ) or {}

        usage = (
            _normalize_usage(raw.get("usage"))
            if isinstance(raw, dict)
            else None
        )

        if usage:
            usage_events.append({
                "source": f"{config.name}_slot_extraction",
                "usage": usage,
            })

    except Exception as e:
        logger.warning(
            f"[Graph] {config.name} extraction failed: {e}"
        )
        parsed = {}

    action = parsed.get("action", "provide_info")
    action = _guard_cancel_action(config, action, query, parsed)

    if action == "cancel":
        slot_store.clear_slots(
            config.name,
            company_id,
            conversation_id,
        )

        return _finish(
            f"No problem, I've cancelled the {label} request.",
            intent=f"{config.name}_cancelled",
        )

    target_employee = (
        parsed.get("employee_name")
        or existing_slots.get("employee_name")
    )

    merged = dict(existing_slots)

    for f in config.required_fields:
        value = parsed.get(f)

        if value:
            merged[f] = value

    if target_employee:
        merged["employee_name"] = target_employee

    missing = [
        f
        for f in config.required_fields
        if not merged.get(f)
    ]

    if action == "confirm":

        if missing:
            slot_store.set_slots(
                config.name,
                company_id,
                conversation_id,
                merged,
            )

            return _finish(
                _missing_fields_message(config, missing),
                intent=f"{config.name}_incomplete",
            )

        writer({
            "type": f"submitting_{config.name}",
            "message": f"Submitting your {label} request...",
        })

        try:
            result = await config.submit(
                merged,
                bearer_token=bearer_token,
                company_id=company_id,
                conversation_id=conversation_id,
            )

        except Exception as e:
            logger.warning(
                f"[Graph] {config.name} submit failed: {e}"
            )

            custom = (
                config.map_submit_exception(e)
                if config.map_submit_exception
                else None
            )

            return _finish(
                custom
                or "I couldn't reach the HR system right now — "
                   "please try again shortly.",
                intent=f"{config.name}_failed",
            )

        http_status = result.get("http_status")
        body = result.get("body") or {}

        if http_status is not None and http_status >= 400:

            slot_store.set_slots(
                config.name,
                company_id,
                conversation_id,
                merged,
            )

            custom = None
            if config.extract_failure_message:
                custom = config.extract_failure_message(merged, body)
                if inspect.isawaitable(custom):
                    custom = await custom

            failure_message = (
                custom
                or body.get("message")
                or body.get("msg")
                or body.get("error")
                or f"I couldn't submit your {label} request right now."
            )

            return _finish(
                failure_message,
                intent=f"{config.name}_failed",
            )

        slot_store.clear_slots(
            config.name,
            company_id,
            conversation_id,
        )

        return _finish(
            config.format_success(merged, body),
            intent=f"{config.name}_submitted",
            extra_data={
                config.name: merged,
                "erp_response": body,
            },
        )

    slot_store.set_slots(
        config.name,
        company_id,
        conversation_id,
        merged,
    )

    if missing:
        return _finish(
            _missing_fields_message(config, missing),
            intent=f"{config.name}_incomplete",
        )

    writer({
        "type": f"{config.name}_summary",
        "data": merged,
    })

    return _finish(
        config.format_summary(merged),
        intent=f"{config.name}_awaiting_confirmation",
        extra_data={
            config.name: merged,
        },
    )


def _merge_entries(
    existing: list[dict],
    incoming: list[dict],
    entry_key: str,
) -> list[dict]:
    """Always-single-entry merge: this flow tracks one date in progress
    at a time rather than accumulating a list. The LAST entry in
    `incoming` either fills in more fields for the date already pending
    (same key — merged in place, existing values kept unless overridden)
    or names a different date, in which case it REPLACES the pending
    entry outright rather than being appended alongside it. If a single
    message names more than one date, only the last one mentioned
    survives. Product decision: repeatedly asking "regularize <date>"
    for a series of distinct dates was accumulating a growing array and
    re-prompting for every earlier date each turn (observed bug) — the
    fix is to just keep the one date currently being worked on."""
    if not incoming:
        return [dict(e) for e in existing]

    latest = incoming[-1]
    key = latest.get(entry_key)
    if not key:
        return [dict(e) for e in existing]

    match = next((e for e in existing if e.get(entry_key) == key), None)
    if match:
        merged_entry = dict(match)
        merged_entry.update({k: v for k, v in latest.items() if v})
        # CHANGED — a correction clears the stale failure marker; a
        # fresh submit attempt will re-tag it if it fails again.
        merged_entry.pop("_failed", None)
        return [merged_entry]

    return [dict(latest)]


def _missing_entry_fields_message(
    config: SlotFlowConfig,
    entries_missing: list[tuple[dict, list[str]]],
) -> str:
    label = config.name.replace("_", " ")
    parts = []

    for entry, missing in entries_missing:
        date_label = entry.get(config.entry_key) or "one of the dates"
        phrases = [config.entry_field_labels[f] for f in missing]

        if len(phrases) == 1:
            parts.append(f"for {date_label}: {phrases[0]}")
        else:
            parts.append(
                f"for {date_label}: "
                + ", ".join(phrases[:-1])
                + f", and {phrases[-1]}"
            )

    return (
        f"I still need a few more details to submit your {label} "
        f"request — " + "; ".join(parts) + "."
    )


def _entries_missing_to_prompt(
    entries_missing: list[tuple[dict, list[str]]],
    touched_keys: set,
    entry_key: str,
) -> list[tuple[dict, list[str]]]:
    """Narrows which incomplete entries to actually ask about this turn.

    Without this, every reply re-lists every still-incomplete entry from
    earlier turns too — e.g. ask about date A, then the employee adds
    date B, and the follow-up re-asks for A's fields even though the
    employee already saw that question and simply moved on to B first
    (observed bug). Only the entry(ies) touched by the current message
    should be asked about; entries left untouched this turn stay pending
    silently (still visible on the entry card) until the employee's
    message touches them again. Falls back to the full list when the
    message didn't touch any entry (e.g. a bare "ok") so the employee
    still gets a prompt instead of silence.
    """
    if not touched_keys:
        return entries_missing

    touched_missing = [
        (e, m) for e, m in entries_missing if e.get(entry_key) in touched_keys
    ]
    return touched_missing or entries_missing


def _build_entry_cards(
    config: SlotFlowConfig,
    entries: list[dict],
    status: str,
    results: Optional[list[dict]] = None,
) -> dict:
    """Structured, frontend-renderable payload for the multi-entry card:
    one row per entry with current field values, which fields are still
    missing, whether the row is currently editable, and (post-submit)
    that entry's individual result.

    status: "incomplete" | "awaiting_confirmation" | "submitted" |
            "partial" | "failed" | "cancelled"
    """

    def _missing_for(entry):
        return [f for f in config.entry_fields if not entry.get(f)]

    cards = []
    for i, entry in enumerate(entries):
        result = results[i] if results and i < len(results) else None
        cards.append({
            "id": entry.get(config.entry_key) or f"entry_{i}",
            **{f: entry.get(f) for f in config.entry_fields},
            "missing_fields": _missing_for(entry),
            "editable": status in ("incomplete", "awaiting_confirmation"),
            "result": (
                {"ok": result["ok"], "error": result.get("error")}
                if result else None
            ),
        })

    if status == "incomplete":
        actions = ["edit"]
    elif status == "awaiting_confirmation":
        actions = ["edit", "confirm", "cancel"]
    else:
        actions = []

    return {
        "status": status,
        "entries": cards,
        "actions": actions,
    }


async def _run_multi_entry_flow(
    config: SlotFlowConfig,
    state: HRState,
    writer: StreamWriter,
    candidate_dates: Optional[list] = None,   # prefill_entries param REMOVED
) -> dict:

    query = state["query"]
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    usage_events = list(state.get("usage_events", []))
    label = config.name.replace("_", " ")

    def _finish(message, intent=None, extra_data=None):
        data = {"answer": message}
        if extra_data:
            data.update(extra_data)
        writer({
            "type": "done",
            "intent": intent or config.name,
            "is_hr": True,
            "data": data,
            "message": message,
            "usage_events": usage_events,
        })
        return {"response_text": message, "usage_events": usage_events}

    def _emit_card(entries, status, results=None):
        writer({
            "type": f"{config.name}_card",
            "data": _build_entry_cards(config, entries, status, results),
        })

    def _missing_for(entry):
        return [f for f in config.entry_fields if not entry.get(f)]

    today = date.today()

    stored = slot_store.get_slots(
        config.name, company_id, conversation_id,
    ) or {}
    existing_entries = stored.get("entries") or []
    employee_name = stored.get("employee_name")

    # OLD prefill_entries block REMOVED from here entirely.

    try:
        prompt = config.build_prompt(
            query, {"entries": existing_entries}, today, candidate_dates,
        )
        raw = await _call_llm(
            prompt, max_tokens=config.llm_max_tokens, model=INTENT_MODEL,
        )
        parsed = _safe_json_parse(_extract_text(raw)) or {}

        usage = (
            _normalize_usage(raw.get("usage"))
            if isinstance(raw, dict) else None
        )
        if usage:
            usage_events.append({
                "source": f"{config.name}_slot_extraction",
                "usage": usage,
            })
    except Exception as e:
        logger.warning(f"[Graph] {config.name} extraction failed: {e}")
        parsed = {}

    action = parsed.get("action", "provide_info")
    action = _guard_cancel_action(config, action, query, parsed)

    if action == "cancel":
        slot_store.clear_slots(config.name, company_id, conversation_id)
        _emit_card([], "cancelled")
        return _finish(
            f"No problem, I've cancelled the {label} request.",
            intent=f"{config.name}_cancelled",
            extra_data={"is_conceled": True},
        )

    target_employee = parsed.get("employee_name") or employee_name
    incoming_entries = parsed.get("entries") or []

    today_iso = today.strftime("%Y-%m-%d")
    existing_dates = {
        e.get(config.entry_key) for e in existing_entries if e.get(config.entry_key)
    }
    resolvable_existing = [
        e for e in existing_entries
        if _missing_for(e) or e.get("_failed")
    ]

    resolved_incoming = []
    unresolved_updates = []

    for inc in incoming_entries:
        inc_date = inc.get(config.entry_key)
        looks_guessed = (not inc_date) or (
            inc_date == today_iso and today_iso not in existing_dates
        )

        if inc_date and not looks_guessed:
            resolved_incoming.append(inc)
            continue

        if len(resolvable_existing) == 1:
            inc[config.entry_key] = resolvable_existing[0][config.entry_key]
            resolved_incoming.append(inc)
        else:
            unresolved_updates.append(inc)

    if unresolved_updates:
        slot_store.set_slots(
            config.name, company_id, conversation_id,
            {"entries": existing_entries, "employee_name": target_employee},
        )
        pending_status = (
            "incomplete" if any(_missing_for(e) for e in existing_entries)
            else "awaiting_confirmation"
        )
        _emit_card(existing_entries, pending_status)

        if resolvable_existing:
            dates_str = ", ".join(
                e.get(config.entry_key) for e in resolvable_existing
            )
            msg = (
                f"I have more than one {label} entry in progress "
                f"({dates_str}) — which date does this update apply to?"
            )
        else:
            msg = (
                f"I couldn't tell which date that's for — "
                f"could you tell me the date as well?"
            )
        return _finish(msg, intent=f"{config.name}_incomplete")

    incoming_entries = resolved_incoming

    # Only the last-mentioned date actually survives the merge below —
    # keep touched_keys in sync so the "ask about what changed" message
    # (see _entries_missing_to_prompt) matches what's actually pending.
    touched_keys = (
        {incoming_entries[-1].get(config.entry_key)}
        if incoming_entries and incoming_entries[-1].get(config.entry_key)
        else set()
    )

    merged_entries = _merge_entries(
        existing_entries, incoming_entries, config.entry_key,
    )

    # NEW — fetch prefill using THIS TURN's merged entries, so a date
    # parsed out of the current message is covered on the same turn.
    if config.fetch_entry_prefill:
        for entry in merged_entries:
            if entry.get("_prefill_fetched") or not _missing_for(entry):
                continue
            try:
                prefill = await config.fetch_entry_prefill(entry, writer)
            except Exception as e:
                logger.warning(
                    f"[Graph] {config.name} prefill fetch failed for "
                    f"{entry.get(config.entry_key)}: {e}"
                )
                prefill = None
            entry["_prefill_fetched"] = True
            if prefill:
                for k, v in prefill.items():
                    if v and not entry.get(k):
                        entry[k] = v

    entries_missing = [
        (e, m) for e in merged_entries for m in [_missing_for(e)] if m
    ]

    if action == "confirm":
        if not merged_entries or entries_missing:
            slot_store.set_slots(
                config.name, company_id, conversation_id,
                {"entries": merged_entries, "employee_name": target_employee},
            )
            _emit_card(merged_entries, "incomplete")
            msg = (
                _missing_entry_fields_message(config, entries_missing)
                if entries_missing else
                f"I don't have any {label} details to submit yet — "
                f"could you tell me the date(s)?"
            )
            return _finish(msg, intent=f"{config.name}_incomplete")

        writer({
            "type": f"submitting_{config.name}",
            "message": f"Submitting your {label} request...",
        })

        results = []
        for entry in merged_entries:
            full_entry = dict(entry)
            if target_employee:
                full_entry["employee_name"] = target_employee

            try:
                result = await config.submit(
                    full_entry,
                    bearer_token=bearer_token,
                    company_id=company_id,
                    conversation_id=conversation_id,
                )
                http_status = result.get("http_status")
                body = result.get("body") or {}

                if http_status is not None and http_status >= 400:
                    custom = None
                    if config.extract_failure_message:
                        custom = config.extract_failure_message(entry, body)
                        if inspect.isawaitable(custom):
                            custom = await custom

                    err = (
                        custom or body.get("message") or body.get("msg")
                        or body.get("error") or "Submission failed."
                    )
                    results.append({"ok": False, "body": body, "error": err})
                else:
                    results.append({"ok": True, "body": body, "error": None})

            except Exception as e:
                logger.warning(
                    f"[Graph] {config.name} submit failed for "
                    f"{entry.get(config.entry_key)}: {e}"
                )
                custom = (
                    config.map_submit_exception(e)
                    if config.map_submit_exception else None
                )
                results.append({
                    "ok": False, "body": {},
                    "error": custom or "Couldn't reach the HR system.",
                })

        failed_entries = [
            e for e, r in zip(merged_entries, results) if not r["ok"]
        ]

        # NEW — mark failed entries so a same-turn dateless correction
        # can still be resolved to this entry on the next turn.
        for e, r in zip(merged_entries, results):
            if not r["ok"]:
                e["_failed"] = True
            else:
                e.pop("_failed", None)

        if failed_entries:
            slot_store.set_slots(
                config.name, company_id, conversation_id,
                {"entries": failed_entries, "employee_name": target_employee},
            )
        else:
            slot_store.clear_slots(config.name, company_id, conversation_id)

        status = "submitted" if not failed_entries else "partial"
        _emit_card(merged_entries, status, results)

        return _finish(
            config.format_multi_success(merged_entries, results),
            intent=f"{config.name}_{status}",
            extra_data={
                config.name: merged_entries,
                "results": results,
                "is_conceled": False,
            },
        )

    # provide_info
    slot_store.set_slots(
        config.name, company_id, conversation_id,
        {"entries": merged_entries, "employee_name": target_employee},
    )

    if not merged_entries:
        _emit_card([], "incomplete")
        return _finish(
            "Sure — which date(s) would you like to regularize?",
            intent=f"{config.name}_incomplete",
        )

    status = "incomplete" if entries_missing else "awaiting_confirmation"
    _emit_card(merged_entries, status)

    if entries_missing:
        prompt_missing = _entries_missing_to_prompt(
            entries_missing, touched_keys, config.entry_key,
        )
        return _finish(
            _missing_entry_fields_message(config, prompt_missing),
            intent=f"{config.name}_incomplete",
        )

    writer({"type": f"{config.name}_summary", "data": merged_entries})

    return _finish(
        config.format_multi_summary(merged_entries),
        intent=f"{config.name}_awaiting_confirmation",
        extra_data={config.name: merged_entries, "is_conceled": False},
    )