from __future__ import annotations
import hashlib
import json
import math
import re
import unicodedata
from collections.abc import Sequence
from itertools import pairwise
from typing import Any
from . import receipt_totals as base

canonical = base.canonical
BOOLEAN_EBNF = 'root ::= "true" | "false" | "null"'
MAX_DECISIONS = base.MAX_BLOCKS


def metadata_spans(source: str) -> list[tuple[int, int]]:
    spans = [(item.start, item.end) for item in base.source_dates.candidates(source)]
    spans.extend(
        (
            match.span()
            for match in base._REFERENCE.finditer(source)
            if re.match("[a-z]+", match[0], re.IGNORECASE)[0].upper()
            not in base.sums._CURRENCY_CODES
        )
    )
    spans.extend(
        (
            match.span()
            for pattern in (
                base._MEASUREMENT,
                base._DISTANCE_RATE,
                base._CARD_REFERENCE,
                base._CONFIRMATION,
                base._CLOCK,
                base._SHORT_DATE,
                base._DATE_CELL,
            )
            for match in pattern.finditer(source)
        )
    )
    return spans


def unresolved_record_coverage(
    source: str, start: int, end: int, monetary: Sequence[dict[str, Any]]
) -> list[dict[str, Any]]:

    def component_label(item: dict[str, Any], lower: int) -> re.Match[str] | None:
        left = item["span"][0]
        for label in base._COMPONENT.finditer(source, max(lower, left - 48), left):
            gap = "".join(
                (
                    "$" if unicodedata.category(char) == "Sc" else char
                    for char in source[label.end() : left]
                )
            )
            if base._BRIDGE.fullmatch(gap):
                return label
        return None

    def metadata_marker(match: re.Match[str]) -> bool:
        line_end = source.find("\n", match.end(), end)
        line_end = end if line_end < 0 else line_end
        if any((match.end() <= item["span"][0] < line_end for item in monetary)):
            return False
        return bool(
            re.match(
                "[ \\t]+(?:method|reference|confirmation|booking|card|date|time)\\b",
                source[match.end() : line_end],
                re.IGNORECASE,
            )
        )

    markers = [
        match
        for match in base._RECORD.finditer(source, start, end)
        if not metadata_marker(match)
    ]
    boundaries = {start, end, *(match.start() for match in markers)}
    metadata = metadata_spans(source)
    for previous, following in pairwise(monetary):
        if component_label(following, start) is None:
            continue
        (left, right) = (previous["span"][1], following["span"][0])
        for line in re.compile("(?m)^[^\\n]*\\n").finditer(source, left, right):
            if any(
                (
                    lower < line.end() and line.start() < upper
                    for (lower, upper) in metadata
                )
            ):
                continue
            gap = "".join(
                (
                    " " if unicodedata.category(char) == "Sc" else char
                    for char in line[0]
                )
            )
            for pattern in (
                base._TOTAL,
                base._COMPONENT,
                base._COMPONENT_CONNECTOR,
                base._CURRENCY_CODE,
            ):
                gap = pattern.sub(" ", gap)
            if not base._AMOUNT_GAP.fullmatch(gap) and (
                not base._RECORD.search(line[0])
            ):
                boundaries.add(line.start())
    marker_starts = {match.start() for match in markers}
    unresolved = []
    for lower, upper in pairwise(sorted(boundaries)):
        amounts = [item for item in monetary if lower <= item["span"][0] < upper]
        if not amounts:
            if lower in marker_starts:
                unresolved.append(
                    {
                        "span": [lower, upper],
                        "text": source[lower:upper],
                        "reason": "record_without_numeric_total_candidate",
                    }
                )
            continue
        labels = [component_label(item, lower) for item in amounts]
        structured = lower in marker_starts or all(
            (
                label is not None
                and (
                    not source[
                        max(
                            lower, source.rfind("\n", lower, label.start()) + 1
                        ) : label.start()
                    ].strip()
                )
                for label in labels
            )
        )
        if structured and all((label is not None for label in labels)):
            unresolved.append(
                {
                    "span": [lower, upper],
                    "text": source[lower:upper],
                    "reason": "component_amounts_without_whole_total_candidate",
                    "occurrence_ids": [item["id"] for item in amounts],
                }
            )
    return unresolved


def inventory(
    task: dict[str, Any],
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
    source = task["input_text"]
    metadata = metadata_spans(source)
    (paragraphs, unresolved, unresolved_coverage) = ([], [], [])
    for start, end in base._paragraphs(source):
        numbers = [
            item for item in task["candidates"] if start <= item["span"][0] < end
        ]

        def non_amount(item: dict[str, Any]) -> bool:
            (left, right) = item["span"]
            return any(
                (
                    right <= upper
                    and (lower <= left or not source[left:lower].strip(" \t+-"))
                    for (lower, upper) in metadata
                )
            )

        monetary = [item for item in numbers if not non_amount(item)]
        blocks = base._blocks(task, paragraphs=((start, end),))
        if blocks:
            candidates = [
                {
                    "kind": "whole_total",
                    "occurrence": block["total_occurrence"],
                    "source_block": block,
                }
                for block in blocks
            ]
        elif monetary:
            unresolved_coverage.extend(
                unresolved_record_coverage(source, start, end, monetary)
            )
            candidates = [
                {
                    "kind": "unresolved_occurrence",
                    "occurrence": {key: item[key] for key in ("id", "span", "printed")},
                }
                for item in monetary
            ]
        else:
            text = source[start:end]
            if (
                base._RECORD.search(text)
                or base._TOTAL.search(text)
                or base._CURRENCY_CODE.search(text)
                or any((unicodedata.category(char) == "Sc" for char in text))
            ):
                unresolved.append({"span": [start, end], "text": text})
            continue
        paragraphs.append(
            {
                "span": [start, end],
                "text": source[start:end],
                "candidates": candidates,
                "numeric_occurrence_ids": [item["id"] for item in numbers],
                "metadata_occurrence_ids": [
                    item["id"] for item in numbers if non_amount(item)
                ],
                "monetary_occurrence_ids": [item["id"] for item in monetary],
            }
        )
    return (paragraphs, unresolved, unresolved_coverage)


def _from_sum_task(task: dict[str, Any]) -> dict[str, Any] | None:
    (paragraphs, unresolved, unresolved_coverage) = inventory(task)
    if unresolved_coverage:
        return None
    descriptors = []
    for paragraph in paragraphs:
        for candidate in paragraph["candidates"]:
            descriptors.append(
                {
                    **candidate,
                    "paragraph_span": paragraph["span"],
                    "source_paragraph": paragraph["text"],
                }
            )
    if not descriptors or len(descriptors) > MAX_DECISIONS:
        return None
    prefix = (
        "Classify each source block using the entire supplied document.\nOriginal document:\n"
        + task["input_text"]
        + "\n\nRequested numeric field: "
        + task["field"]
        + "\nOriginal field schema and instructions: "
        + json.dumps(task["field_spec"], ensure_ascii=False, separators=(",", ":"))
        + "\nDecide whether the candidate block is one receipt record in the requested sum. Use its category, entity, date and the original requested scope. Return true if and only if this record's explicit total is one requested operand. A total label alone does not establish inclusion. Hotel, airline and claim-summary blocks remain candidates; include them only when the requested receipt scope includes them. A claim summary is not an additional underlying receipt. Do not separately select food, subtotal, tax, tip or other components already included in a total. A zero or refund remains a present amount. Distinct source records remain distinct even with equal totals. Do not calculate the sum. Return false for an excluded record; return null if the evidence does not determine its inclusion. No expected values are supplied. Return exactly one JSON Boolean or null, then end immediately.\n"
    )
    prefix += "When the candidate marks one exact occurrence, evaluate only that marked occurrence as a whole receipt total; its paragraph may contain multiple records or totals. Every candidate still requires its own category, entity, date and requested-scope decision.\n"
    tasks = []
    for descriptor in descriptors:
        if descriptor["kind"] == "whole_total":
            suffix = "\nCandidate source block: " + json.dumps(
                descriptor["source_block"], ensure_ascii=False, separators=(",", ":")
            )
        else:
            suffix = "\nCandidate exact source occurrence: " + json.dumps(
                descriptor, ensure_ascii=False, separators=(",", ":")
            )
        tasks.append(
            {
                "occurrence_id": descriptor["occurrence"]["id"],
                "prompt": prefix + suffix,
                "suffix": suffix,
                "json_schema": {"type": ["boolean", "null"]},
                "grammar": {"ebnf": BOOLEAN_EBNF},
            }
        )
    assert len({task["occurrence_id"] for task in tasks}) == len(tasks)
    return {
        "version": 1,
        "kind": "receipt-hybrid-paragraph-runtime-v1",
        "sum_task": task,
        "paragraphs": paragraphs,
        "descriptors": descriptors,
        "tasks": tasks,
        "currency_compatible": base._compatible_currencies(
            task, [{"source_block": row["text"]} for row in paragraphs]
        ),
        "unresolved_fragments_without_numeric_candidates": unresolved,
        "shared_prefix": prefix,
        "shared_prefix_sha256": hashlib.sha256(prefix.encode()).hexdigest(),
        "diagnostic_only": False,
        "public_repair_path": True,
        "serving_admission_requires_backend_guard": True,
        "runtime_changes": True,
        "all_candidates_require_complete_decisions": True,
        "native_typed_boolean_head": False,
        "semantic_completeness_proven_by_grounding": False,
    }


def prepare_task(
    record: dict[str, Any], field_name: str, *, has_media: bool = False
) -> dict[str, Any] | None:
    if not base.eligible(record, field_name, has_media=has_media):
        return None
    task = base.sums.prepare_task(record, field_name, has_media=has_media)
    return None if task is None else _from_sum_task(task)


def validate_result(
    packet: dict[str, Any], decisions: dict[str, dict[str, Any]]
) -> dict[str, Any]:
    result: dict[str, Any] = {
        "valid": False,
        "value": None,
        "error": None,
        "decision_count": 0,
        "required_decision_count": len(packet.get("tasks", [])),
        "diagnostic_only": False,
        "public_repair_path": True,
        "serving_admission_requires_backend_guard": True,
        "backend_constructs_public_answer": True,
        "semantic_completeness_proven_by_grounding": False,
    }
    try:
        task = packet["sum_task"]
        rebuilt = base.prepare_task(
            {
                "input": task["input_text"],
                "fields": {task["field"]: task["field_spec"]},
            },
            task["field"],
        )
        if rebuilt is None or canonical(rebuilt) != canonical(packet):
            raise ValueError("hybrid_packet_prompt_or_source_mapping_changed")
        if packet["unresolved_fragments_without_numeric_candidates"]:
            raise ValueError("unresolved_fragment_without_numeric_candidate")
        expected = [item["occurrence_id"] for item in packet["tasks"]]
        if not isinstance(decisions, dict) or set(decisions) != set(expected):
            raise ValueError("hybrid_decision_coverage_incomplete_or_extra")
        selected = []
        for identifier in expected:
            reading = decisions[identifier]
            value = json.loads(
                reading["raw_json"],
                parse_constant=lambda _: (_ for _ in ()).throw(
                    ValueError("nonfinite_json")
                ),
            )
            if type(value) is not bool or reading.get("complete") is not True:
                raise ValueError("unresolved_or_incomplete_boolean:" + identifier)
            score: Any
            confidence: Any
            (score, confidence) = (
                reading.get("log_probability"),
                reading.get("confidence"),
            )
            if (
                type(score) not in (int, float)
                or not math.isfinite(score)
                or score > 0
                or (type(confidence) not in (int, float))
                or (not math.isfinite(confidence))
                or (not 0 <= confidence <= 1)
                or (
                    not math.isclose(
                        confidence, math.exp(score), rel_tol=2e-15, abs_tol=0
                    )
                )
                or (type(reading.get("tokens")) is not int)
                or (not 1 <= reading["tokens"] <= 8)
            ):
                raise ValueError(
                    "native_boolean_score_or_token_contract_failed:" + identifier
                )
            result["decision_count"] += 1
            if value:
                selected.append(identifier)
        scores = base._selection_scores(decisions, expected)
        if scores is None:
            raise ValueError("native_joint_boolean_scores_required")
        if not packet["currency_compatible"]:
            raise ValueError("explicit_currency_conflict_no_conversion")
        checked = base.sums.validate_result(
            task, json.dumps(selected) if selected else "null", complete=True
        )
        result.update(checked, selected_ids=selected, selection_scores=scores)
    except (ArithmeticError, AttributeError, KeyError, TypeError, ValueError) as error:
        result.update(valid=False, value=None, error=str(error) or type(error).__name__)
    return result
