"""Offline advisory-to-inventory triage example; it does not call an API."""

from __future__ import annotations

import argparse
import csv
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any


FAMILIES = ("ASA", "IOS", "Nexus")
IDENTITY_FIELDS = ("family", "version", "platform", "mode")
INVENTORY_FIELDS = set(IDENTITY_FIELDS)
TARGET_FIELDS = {"ticket", "advisory_id", "title"}
RESULT_FIELDS = set(IDENTITY_FIELDS) | {
    "status", "all_pages", "version_valid", "advisory_ids", "checked_at"
}
CSV_FIELDS = (
    "ticket", "advisory_id", "family", "version", "platform", "mode",
    "mark", "reason", "checked_at",
)


class InputError(ValueError):
    """Raised when inventory or target definitions cannot be interpreted."""


def _nonempty_string(value: Any) -> bool:
    return isinstance(value, str) and bool(value.strip())


def _identity(record: dict[str, Any]) -> tuple[str, str, str, str]:
    return tuple(record[field] for field in IDENTITY_FIELDS)  # type: ignore[return-value]


def _valid_identity(record: dict[str, Any]) -> bool:
    return (
        record.get("family") in FAMILIES
        and _nonempty_string(record.get("version"))
        and isinstance(record.get("platform"), str)
        and isinstance(record.get("mode"), str)
    )


def validate_inventory(value: Any) -> list[dict[str, str]]:
    if not isinstance(value, list) or not value:
        raise InputError("inventory must be a non-empty JSON array")
    records: list[dict[str, str]] = []
    for index, row in enumerate(value):
        if not isinstance(row, dict) or set(row) != INVENTORY_FIELDS or not _valid_identity(row):
            raise InputError(f"inventory[{index}] has an invalid shape or value")
        records.append({key: row[key] for key in IDENTITY_FIELDS})
    return records


def validate_targets(value: Any) -> list[dict[str, str]]:
    if not isinstance(value, list) or not value:
        raise InputError("targets must be a non-empty JSON array")
    records: list[dict[str, str]] = []
    for index, row in enumerate(value):
        if (
            not isinstance(row, dict)
            or set(row) != TARGET_FIELDS
            or any(not _nonempty_string(row.get(key)) for key in TARGET_FIELDS)
        ):
            raise InputError(f"targets[{index}] has an invalid shape or value")
        records.append({key: row[key] for key in ("ticket", "advisory_id", "title")})
    return records


def _valid_checked_at(value: Any) -> bool:
    if not _nonempty_string(value):
        return False
    try:
        datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError:
        return False
    return True


def _valid_result(row: Any) -> bool:
    return (
        isinstance(row, dict)
        and set(row) == RESULT_FIELDS
        and _valid_identity(row)
        and isinstance(row.get("status"), str)
        and row.get("status") in {"complete", "failed"}
        and type(row.get("all_pages")) is bool
        and type(row.get("version_valid")) is bool
        and isinstance(row.get("advisory_ids"), list)
        and all(_nonempty_string(value) for value in row.get("advisory_ids", []))
        and _valid_checked_at(row.get("checked_at"))
    )


def _result_rows(value: Any) -> tuple[list[dict[str, Any]], bool]:
    """Return normalized rows and whether the result document is untrustworthy."""
    if not isinstance(value, list):
        return [], True
    if any(not _valid_result(row) for row in value):
        # A malformed normalized document cannot support a negative finding.
        return [], True
    return value, False


def classify(inventory: Any, targets: Any, results: Any, family: str = "all") -> list[dict[str, str]]:
    devices = validate_inventory(inventory)
    advisories = validate_targets(targets)
    if family not in (*FAMILIES, "all"):
        raise InputError("family must be ASA, IOS, Nexus, or all")

    selected = [item for item in devices if family == "all" or item["family"] == family]
    if not selected:
        raise InputError(f"inventory contains no devices for family {family}")

    query_rows, malformed_results = _result_rows(results)
    counts: dict[tuple[str, str, str, str], int] = {}
    for item in selected:
        key = _identity(item)
        counts[key] = counts.get(key, 0) + 1

    output: list[dict[str, str]] = []
    for device in selected:
        key = _identity(device)
        matches = [row for row in query_rows if _identity(row) == key]
        for target in advisories:
            mark = "?"
            checked_at = ""
            if malformed_results:
                reason = "照会結果の構造が不正; 要確認"
            elif counts[key] > 1:
                reason = "inventoryの照合キーが重複; 要確認"
            elif not matches:
                reason = "同条件の照会データなし; 要確認"
            elif len(matches) > 1:
                reason = "同条件の照会結果が重複; 要確認"
            else:
                result = matches[0]
                checked_at = result["checked_at"]
                if result["status"] != "complete":
                    reason = "照会失敗; 要確認"
                elif not result["all_pages"]:
                    reason = "全ページ未取得; 要確認"
                elif not result["version_valid"]:
                    reason = "OSバージョン未確認; 要確認"
                elif target["advisory_id"] in result["advisory_ids"]:
                    mark = "○"
                    reason = "同条件の照会結果に対象IDあり; 一次候補"
                else:
                    mark = "×"
                    reason = "完全な同条件結果に対象IDなし; 今回の候補なし"

            output.append({
                "ticket": target["ticket"],
                "advisory_id": target["advisory_id"],
                **device,
                "mode": device["mode"],
                "mark": mark,
                "reason": reason,
                "checked_at": checked_at,
            })
    return output


def excel_safe(value: str) -> str:
    """Prefix formula-like cells so opening the CSV in a spreadsheet is safer."""
    probe = value.lstrip(" \t\r\n\x00")
    if probe.startswith(("=", "+", "-", "@")):
        return "'" + value
    return value


def write_csv(path: Path, rows: list[dict[str, str]]) -> None:
    # Exclusive creation avoids silently replacing evidence or input files.
    with path.open("x", encoding="utf-8-sig", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS, extrasaction="raise")
        writer.writeheader()
        writer.writerows({key: excel_safe(row[key]) for key in CSV_FIELDS} for row in rows)


def _read_json(path: Path) -> Any:
    with path.open("r", encoding="utf-8") as handle:
        return json.load(handle)


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Offline advisory triage against a device inventory")
    parser.add_argument("--family", required=True, choices=(*FAMILIES, "all"))
    parser.add_argument("--inventory", required=True, type=Path)
    parser.add_argument("--targets", required=True, type=Path)
    parser.add_argument("--results", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    args = parser.parse_args(argv)

    try:
        inventory = _read_json(args.inventory)
        targets = _read_json(args.targets)
        results = _read_json(args.results)
        rows = classify(inventory, targets, results, args.family)
        write_csv(args.output, rows)
    except (OSError, json.JSONDecodeError, InputError, csv.Error) as error:
        print(f"triage: {error}", file=sys.stderr)
        return 2
    print(f"Wrote {len(rows)} rows to {args.output}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
