#!/usr/bin/env python3
"""Extract a declared product table from the HTML in a Saffron /v1/scrape response."""

import argparse
import hashlib
import json
import os
import re
import sys
import tempfile
import unicodedata
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import urlsplit

# The supported contract uses these currency scales and unsigned, ungrouped prices.
SCALES = {"USD": 2, "EUR": 2, "GBP": 2, "CAD": 2, "AUD": 2, "CHF": 2, "JPY": 0, "KWD": 3}
DEFAULT_COLUMNS = {"id": "SKU", "name": "Name", "price": "Price", "currency": "Currency"}
VOID = {
    "area",
    "base",
    "br",
    "col",
    "embed",
    "hr",
    "img",
    "input",
    "link",
    "meta",
    "param",
    "source",
    "track",
    "wbr",
}
SKIP = {"script", "style", "template", "noscript"}
MAX_SAFE_INTEGER = 9007199254740991
MAX_CAPTURE_BYTES = 16 * 1024 * 1024


class Rejected(ValueError):
    def __init__(self, code, message, row=None, field=None):
        super().__init__(message)
        self.issue = {"code": code, "message": message}
        if row is not None:
            self.issue["dataRow"] = row
        if field is not None:
            self.issue["field"] = field


def digest(data):
    return hashlib.sha256(data).hexdigest()


def normalize(text):
    return " ".join(text.split())


def unique_object(pairs):
    data = {}
    for key, value in pairs:
        if key in data:
            raise Rejected("DUPLICATE_JSON_FIELD", "Input contains a repeated JSON field.")
        data[key] = value
    return data


def decode_json(raw):
    def invalid_number(_):
        raise Rejected("INVALID_JSON", "JSON cannot contain a non-finite number token.")

    try:
        return json.loads(
            raw.decode("utf-8-sig"), object_pairs_hook=unique_object, parse_constant=invalid_number
        )
    except Rejected:
        raise
    except (ValueError, RecursionError) as err:
        raise Rejected("INVALID_JSON", "Expected a UTF-8 JSON document.") from err


class Table(HTMLParser):
    """Read already serialized browser DOM. Refuse structural ambiguity in the chosen table."""

    def __init__(self, table_id):
        super().__init__(convert_charrefs=True)
        self.table_id = table_id
        self.found = False
        self.active = False
        self.ignored = []
        self.rows = []
        self.row = None
        self.cell = None

    def handle_starttag(self, tag, attrs):
        attr = dict(attrs)
        style = attr.get("style") or ""
        explicitly_hidden = re.search(
            r"(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*(?:hidden|collapse))\s*(?:!\s*important\s*)?(?:;|$)",
            style,
            re.IGNORECASE,
        )
        ignored = (
            tag in SKIP
            or "hidden" in attr
            or (attr.get("aria-hidden") or "").lower() == "true"
            or explicitly_hidden
        )
        if self.ignored or ignored:
            if not self.ignored and self.active and tag in ("td", "th"):
                raise Rejected("HIDDEN_COLUMN", "The selected table contains a hidden cell.")
            if tag not in VOID:
                self.ignored.append(tag)
            return
        ids = [v for k, v in attrs if k == "id"]
        if self.table_id in ids and tag != "table":
            raise Rejected(
                "AMBIGUOUS_TABLE", "The selected table ID also identifies a different element."
            )
        if tag == "table":
            if self.active:
                raise Rejected("NESTED_TABLE", "The selected table contains a nested table.")
            if self.table_id not in ids:
                return
            if self.found or len(ids) != 1:
                raise Rejected("AMBIGUOUS_TABLE", "Expected one visible table with this ID.")
            self.active = self.found = True
        if not self.active:
            return
        if (attr.get("aria-busy") or "").lower() == "true":
            raise Rejected("TABLE_BUSY", "The captured table still reports that it is loading.")
        if tag == "tr":
            if self.row is not None:
                raise Rejected("INVALID_TABLE", "A table row was left open.")
            self.row = []
        elif tag in ("td", "th"):
            if self.row is None or self.cell is not None:
                raise Rejected("INVALID_TABLE", "A cell is outside its row or contains another cell.")
            if any(v != "1" for k, v in attrs if k in ("colspan", "rowspan")):
                raise Rejected("SPANNED_CELL", "Merged table cells do not identify a unique column.")
            self.cell = {"tag": tag, "parts": [], "struck": False}
        elif self.cell is not None:
            if tag in ("s", "del", "strike"):
                self.cell["struck"] = True
            if tag == "br":
                self.cell["parts"].append(" ")

    def handle_endtag(self, tag):
        if self.ignored:
            if tag == self.ignored[-1]:
                self.ignored.pop()
            return
        if not self.active:
            return
        if tag in ("td", "th"):
            if self.cell is None or self.cell["tag"] != tag:
                raise Rejected("INVALID_TABLE", "An unexpected closing cell was found.")
            self.row.append(self.cell)
            self.cell = None
        elif tag == "tr":
            if self.row is None or self.cell is not None:
                raise Rejected("INVALID_TABLE", "The selected table has an incomplete row.")
            self.rows.append(self.row)
            self.row = None
        elif tag == "table":
            if self.row is not None:
                raise Rejected("INVALID_TABLE", "The selected table has an incomplete row.")
            self.active = False

    def handle_data(self, text):
        if not self.ignored and self.cell is not None:
            self.cell["parts"].append(text)


def field_text(cell, row, field):
    parts = [p.strip() for p in cell["parts"] if p.strip()]
    if not parts:
        raise Rejected("MISSING_VALUE", "The required cell is empty.", row, field)
    if cell["struck"] or (field != "name" and len(parts) != 1):
        raise Rejected(
            "AMBIGUOUS_VALUE", "The cell contains struck or multiple candidate values.", row, field
        )
    return normalize("".join(cell["parts"])) if field == "name" else parts[0]


def amount(text, currency, row):
    if currency not in SCALES:
        raise Rejected(
            "UNSUPPORTED_CURRENCY", "Use a supported uppercase currency code.", row, "currency"
        )
    if not re.fullmatch(r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?", text):
        raise Rejected(
            "INVALID_PRICE",
            "Use an unsigned decimal without grouping or a currency symbol.",
            row,
            "price",
        )
    units, _, fraction = text.partition(".")
    scale = SCALES[currency]
    if len(fraction) > scale:
        raise Rejected(
            "PRICE_PRECISION", "The price exceeds this currency's supported scale.", row, "price"
        )
    if len(units) > 16:
        raise Rejected(
            "PRICE_OUT_OF_RANGE",
            "The minor-unit value exceeds the JSON safe integer range.",
            row,
            "price",
        )
    decimals = fraction.ljust(scale, "0")
    minor = int(units + decimals)
    if minor > MAX_SAFE_INTEGER:
        raise Rejected(
            "PRICE_OUT_OF_RANGE",
            "The minor-unit value exceeds the JSON safe integer range.",
            row,
            "price",
        )
    return {
        "amount": units + ("." + decimals if scale else ""),
        "currency": currency,
        "minorUnits": minor,
    }


def id_key(value):
    return unicodedata.normalize("NFC", value)


def expected_set(expected):
    if not isinstance(expected, list) or not expected:
        raise Rejected("INVALID_ROSTER", "Provide a nonempty JSON array of unique string product IDs.")
    ids = set()
    for value in expected:
        if (
            not isinstance(value, str)
            or not value
            or any(ch.isspace() or unicodedata.category(ch) in ("Cc", "Cf", "Cs") for ch in value)
        ):
            raise Rejected(
                "INVALID_ROSTER", "Roster IDs must be nonempty strings without whitespace or controls."
            )
        key = id_key(value)
        if key in ids:
            raise Rejected("INVALID_ROSTER", "The roster repeats a product ID.")
        ids.add(key)
    return ids


def extract_catalog(raw, table_id="catalog", columns=None, expected_ids=None):
    """Return validated JSON-ready data or raise Rejected. No network or filesystem access."""
    if not isinstance(table_id, str) or not table_id or any(c.isspace() for c in table_id):
        raise Rejected("INVALID_TABLE_ID", "Provide a nonempty table ID without whitespace.")
    columns = DEFAULT_COLUMNS if columns is None else columns
    if (
        not isinstance(columns, dict)
        or set(columns) != set(DEFAULT_COLUMNS)
        or any(not isinstance(c, str) or not normalize(c) for c in columns.values())
    ):
        raise Rejected("INVALID_COLUMNS", "Specify one column heading for each required product field.")
    selected = {key: normalize(name).casefold() for key, name in columns.items()}
    if len(set(selected.values())) != len(selected):
        raise Rejected("INVALID_COLUMNS", "The four fields must use distinct column headings.")
    if not isinstance(raw, bytes):
        raise Rejected("INVALID_INPUT", "Pass the original response bytes.")
    if len(raw) > MAX_CAPTURE_BYTES:
        raise Rejected("CAPTURE_TOO_LARGE", "The input exceeds the 16 MiB capture limit.")
    source = decode_json(raw)
    if not isinstance(source, dict) or source.get("ok") is not True:
        raise Rejected("CAPTURE_FAILED", "Expected a successful top-level /v1/scrape response.")
    if type(source.get("status")) is not int or not 200 <= source["status"] < 300:
        raise Rejected("TARGET_FAILED", "The captured page did not return a 2xx target status.")
    html, url = source.get("html"), source.get("url")
    if not isinstance(html, str) or not html.strip():
        raise Rejected("MISSING_HTML", "The response does not contain rendered HTML.")
    if not isinstance(url, str):
        raise Rejected("MISSING_SOURCE_URL", "The response must identify the final captured URL.")
    try:
        parsed = urlsplit(url)
        valid_url = (
            parsed.scheme in ("http", "https")
            and bool(parsed.hostname)
            and parsed.username is None
            and parsed.password is None
        )
        # Accessing port checks its numeric range in urllib.
        valid_url = valid_url and (parsed.port is None or parsed.port >= 0)
        url.encode("utf-8")
        valid_url = valid_url and not any(ch.isspace() or unicodedata.category(ch) == "Cc" for ch in url)
        html_bytes = html.encode("utf-8")
    except (ValueError, UnicodeEncodeError) as err:
        raise Rejected("INVALID_SOURCE", "Invalid source URL or Unicode HTML.") from err
    if not valid_url:
        raise Rejected(
            "INVALID_SOURCE_URL", "Expected an HTTP(S) source URL without embedded credentials."
        )
    table = Table(table_id)
    try:
        table.feed(html)
        table.close()
    except (AssertionError, NotImplementedError) as err:
        raise Rejected("INVALID_HTML", "The serialized DOM contains an invalid declaration.") from err
    if not table.found:
        raise Rejected("TABLE_NOT_FOUND", "The requested table was absent from the capture.")
    if table.active:
        raise Rejected("INVALID_TABLE", "The selected table was not closed.")
    if len(table.rows) < 2:
        raise Rejected("NO_PRODUCTS", "The captured table has no complete product rows.")
    header = table.rows[0]
    if not header or any(cell["tag"] != "th" for cell in header):
        raise Rejected("INVALID_HEADER", "The first row must consist of named header cells.")
    names = [normalize("".join(c["parts"])) for c in header]
    folded = [name.casefold() for name in names]
    positions = {}
    for field, name in selected.items():
        if folded.count(name) != 1:
            raise Rejected(
                "COLUMN_NOT_UNIQUE", "A required heading is missing or repeated.", field=field
            )
        positions[field] = folded.index(name)
    products, seen = [], set()
    for row, cells in enumerate(table.rows[1:], 1):
        if len(cells) != len(header):
            raise Rejected("ROW_WIDTH", "The row's cell count differs from the header.", row)
        values = {k: field_text(cells[index], row, k) for k, index in positions.items()}
        ident = values["id"]
        if any(ch.isspace() or unicodedata.category(ch) in ("Cc", "Cf", "Cs") for ch in ident):
            raise Rejected(
                "INVALID_PRODUCT_ID", "A product ID contains whitespace or controls.", row, "id"
            )
        key = id_key(ident)
        if key in seen:
            raise Rejected("DUPLICATE_PRODUCT_ID", "The captured table repeats a product ID.", row, "id")
        seen.add(key)
        products.append(
            {
                "id": ident,
                "name": values["name"],
                "price": amount(values["price"], values["currency"], row),
                "provenance": {
                    "dataRow": row,
                    "rawPrice": values["price"],
                    "rawCurrency": values["currency"],
                },
            }
        )
    roster = expected_set(expected_ids) if expected_ids is not None else None
    if roster is not None and roster != seen:
        raise Rejected(
            "ROSTER_MISMATCH",
            f"Captured rows differ from the roster ({len(roster - seen)} missing, {len(seen - roster)} unexpected).",
        )
    return {
        "schemaVersion": "saffron.catalog.v1",
        "coverage": "expected_ids_matched" if roster is not None else "observed_rows",
        "source": {
            "url": url,
            "targetStatus": source["status"],
            "captureSha256": digest(raw),
            "htmlSha256": digest(html_bytes),
            "tableId": table_id,
            "columns": {k: names[index] for k, index in positions.items()},
        },
        "productCount": len(products),
        "products": products,
    }


def write_atomic(path, data):
    tmp = None
    try:
        with tempfile.NamedTemporaryFile(
            dir=path.parent, prefix="." + path.name + ".", delete=False
        ) as f:
            tmp = Path(f.name)
            f.write(data)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, path)
    finally:
        if tmp is not None:
            tmp.unlink(missing_ok=True)


def main():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument("--input", type=Path, help="saved JSON capture (default: stdin)")
    cli.add_argument(
        "--output", type=Path, help="atomically replace this file only on success (default: stdout)"
    )
    cli.add_argument(
        "--expected-ids", type=Path, help="owner-supplied JSON array of the expected string product IDs"
    )
    cli.add_argument("--table-id", default="catalog")
    for field, name in DEFAULT_COLUMNS.items():
        cli.add_argument(
            "--" + field + "-header", default=name, help="column title (default: %(default)s)"
        )
    args = cli.parse_args()
    try:
        if args.output and any(
            source
            and (
                source.resolve() == args.output.resolve()
                or (args.output.exists() and source.exists() and source.samefile(args.output))
            )
            for source in (args.input, args.expected_ids)
        ):
            raise Rejected(
                "OUTPUT_COLLISION", "Choose an output file separate from the capture and roster."
            )
        if args.input:
            with args.input.open("rb") as f:
                raw = f.read(MAX_CAPTURE_BYTES + 1)
        else:
            raw = sys.stdin.buffer.read(MAX_CAPTURE_BYTES + 1)
        expected = None
        if args.expected_ids:
            with args.expected_ids.open("rb") as f:
                roster_bytes = f.read(MAX_CAPTURE_BYTES + 1)
            if len(roster_bytes) > MAX_CAPTURE_BYTES:
                raise Rejected("INVALID_ROSTER", "The roster exceeds the 16 MiB input limit.")
            expected = decode_json(roster_bytes)
            if expected is None:
                raise Rejected("INVALID_ROSTER", "Provide an array of product IDs.")
        result = extract_catalog(
            raw, args.table_id, {k: getattr(args, k + "_header") for k in DEFAULT_COLUMNS}, expected
        )
        encoded = (json.dumps(result, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
        if args.output:
            write_atomic(args.output, encoded)
        else:
            sys.stdout.buffer.write(encoded)
        return 0
    except Rejected as err:
        print(json.dumps({"ok": False, "error": err.issue}, ensure_ascii=False), file=sys.stderr)
        return 2
    except OSError as err:
        print(
            json.dumps({"ok": False, "error": {"code": "IO_ERROR", "message": str(err)}}),
            file=sys.stderr,
        )
        return 1


if __name__ == "__main__":
    sys.exit(main())
