#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 AIM SHIELD
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions: the above copyright notice and
# this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED
# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Validador autocontenido de «Señal de estafa» v0 (solo biblioteca estándar de Python 3.9 o posterior).

Uso:  python3 senal_validar.py senal.json       (una señal, una lista de señales o un feed con «senales»)
      python3 senal_validar.py --hash-iban "ES00 0000 0000 0000 0000 0000"
Salida 0 si todo es válido, 1 si hay problemas (se listan), 2 si falla la lectura. El esquema (CC BY 4.0, AIM SHIELD)
va incrustado y es el mismo que https://www.aim-shield.ai/static/esquemas/senal-estafa-v0.json.
"""
import hashlib
import json
import re
import sys
from datetime import datetime

SAL_IBAN = "aim-shield-senal-v0:"
SCHEMA = json.loads(r'''{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://www.aim-shield.ai/static/esquemas/senal-estafa-v0.json",
  "$comment": "Señal de estafa v0. Licencia del esquema: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/), atribución: AIM SHIELD. El validador de referencia se publica con licencia MIT. Este formato no admite datos personales: ni nombres, ni correos, ni teléfonos de particulares, ni IBAN en claro.",
  "title": "Señal de estafa v0",
  "description": "Una estafa que circula, descrita solo con sus pistas técnicas. Sin datos de personas.",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "version",
    "id",
    "tipo",
    "canal",
    "indicadores",
    "visto_por_primera_vez",
    "confianza",
    "fuente"
  ],
  "properties": {
    "version": {
      "const": "0",
      "description": "Versión del formato."
    },
    "id": {
      "type": "string",
      "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
      "description": "UUID de la señal, en minúsculas."
    },
    "tipo": {
      "enum": [
        "phishing",
        "smishing",
        "vishing",
        "suplantacion_marca",
        "inversion",
        "romance",
        "compra_falsa",
        "empleo_falso",
        "recuperacion",
        "ceo_factura",
        "otro"
      ],
      "description": "Tipo de engaño."
    },
    "canal": {
      "enum": [
        "sms",
        "correo",
        "llamada",
        "whatsapp",
        "redes",
        "web",
        "otro"
      ],
      "description": "Por dónde llega."
    },
    "indicadores": {
      "type": "array",
      "minItems": 1,
      "maxItems": 100,
      "description": "Pistas técnicas de la estafa.",
      "items": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "tipo",
          "valor"
        ],
        "properties": {
          "tipo": {
            "enum": [
              "dominio",
              "url",
              "telefono",
              "iban_hash",
              "remitente_sms",
              "correo_dominio",
              "plantilla_hash"
            ]
          },
          "valor": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2048
          }
        },
        "allOf": [
          {
            "if": {
              "properties": {
                "tipo": {
                  "const": "dominio"
                }
              },
              "required": [
                "tipo"
              ]
            },
            "then": {
              "properties": {
                "valor": {
                  "pattern": "^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$"
                }
              }
            }
          },
          {
            "if": {
              "properties": {
                "tipo": {
                  "const": "url"
                }
              },
              "required": [
                "tipo"
              ]
            },
            "then": {
              "properties": {
                "valor": {
                  "pattern": "^(?!.*%40)https?://[^\\s@]{4,2000}$"
                }
              }
            }
          },
          {
            "if": {
              "properties": {
                "tipo": {
                  "const": "telefono"
                }
              },
              "required": [
                "tipo"
              ]
            },
            "then": {
              "properties": {
                "valor": {
                  "pattern": "^\\+[1-9][0-9]{6,14}$"
                }
              }
            }
          },
          {
            "if": {
              "properties": {
                "tipo": {
                  "const": "iban_hash"
                }
              },
              "required": [
                "tipo"
              ]
            },
            "then": {
              "properties": {
                "valor": {
                  "pattern": "^[0-9a-f]{64}$"
                }
              }
            }
          },
          {
            "if": {
              "properties": {
                "tipo": {
                  "const": "plantilla_hash"
                }
              },
              "required": [
                "tipo"
              ]
            },
            "then": {
              "properties": {
                "valor": {
                  "pattern": "^[0-9a-f]{64}$"
                }
              }
            }
          },
          {
            "if": {
              "properties": {
                "tipo": {
                  "const": "remitente_sms"
                }
              },
              "required": [
                "tipo"
              ]
            },
            "then": {
              "properties": {
                "valor": {
                  "pattern": "^(?=.*[A-Za-z])[A-Za-z0-9 ._-]{1,11}$"
                }
              }
            }
          },
          {
            "if": {
              "properties": {
                "tipo": {
                  "const": "correo_dominio"
                }
              },
              "required": [
                "tipo"
              ]
            },
            "then": {
              "properties": {
                "valor": {
                  "pattern": "^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$",
                  "not": {
                    "$ref": "#/$defs/correo_libre"
                  }
                }
              }
            }
          }
        ]
      }
    },
    "marca_suplantada": {
      "type": "string",
      "minLength": 1,
      "maxLength": 100,
      "pattern": "^(?!(?:[^0-9]*[0-9]){8})[^@\\n]+$",
      "description": "Marca o entidad cuya identidad se usa. Nunca el nombre de una persona."
    },
    "visto_por_primera_vez": {
      "type": "string",
      "pattern": "^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?(Z|[+-]([01][0-9]|2[0-3]):[0-5][0-9])$",
      "description": "Fecha y hora ISO 8601 con zona."
    },
    "visto_por_ultima_vez": {
      "type": "string",
      "pattern": "^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?(Z|[+-]([01][0-9]|2[0-3]):[0-5][0-9])$",
      "description": "Fecha y hora ISO 8601 con zona; no anterior a la primera."
    },
    "confianza": {
      "enum": [
        "confirmada",
        "probable",
        "sin_confirmar"
      ]
    },
    "fuente": {
      "enum": [
        "regulador",
        "organismo_oficial",
        "deteccion_automatica",
        "aportacion_ciudadana",
        "colaborador_organizacion",
        "otro"
      ],
      "description": "Tipo de fuente. Nunca la identidad de una persona."
    },
    "idioma": {
      "type": "string",
      "pattern": "^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$",
      "description": "Idioma del engaño (BCP 47)."
    },
    "pais": {
      "type": "string",
      "pattern": "^[A-Z]{2}$",
      "description": "País al que se dirige (ISO 3166-1 alfa-2)."
    }
  },
  "$defs": {
    "correo_libre": {
      "enum": [
        "aol.com",
        "gmail.com",
        "gmx.com",
        "gmx.es",
        "googlemail.com",
        "hotmail.com",
        "hotmail.es",
        "icloud.com",
        "live.com",
        "mail.com",
        "me.com",
        "msn.com",
        "outlook.com",
        "outlook.es",
        "proton.me",
        "protonmail.com",
        "yahoo.com",
        "yahoo.es",
        "yandex.com"
      ],
      "description": "Servicios de correo gratuitos: no son el dominio de una estafa."
    }
  }
}''')
_ANOTACIONES = frozenset({"$schema", "$id", "$comment", "$defs", "title", "description", "format", "examples"})
_VALIDACION = frozenset({"type", "const", "enum", "required", "properties", "additionalProperties", "pattern", "minLength",
                         "maxLength", "minItems", "maxItems", "items", "allOf", "if", "then", "not", "$ref"})
_TIPOS_JSON = {"object": dict, "array": list, "string": str, "boolean": bool, "integer": int, "number": (int, float)}


def hash_iban(iban):
    """Huella de un IBAN: SHA-256 de SAL_IBAN + IBAN sin espacios y en mayúsculas, en hexadecimal."""
    limpio = re.sub(r"\s+", "", str(iban)).upper()
    return hashlib.sha256((SAL_IBAN + limpio).encode("utf-8")).hexdigest()


def _ref(ref):
    nodo = SCHEMA
    for parte in ref.lstrip("#/").split("/"):
        nodo = nodo[parte]
    return nodo


def _comprobar(valor, esq, ruta):
    desconocidas = set(esq) - _ANOTACIONES - _VALIDACION
    if desconocidas:
        raise ValueError("palabra de esquema no admitida: %s" % sorted(desconocidas))
    donde = ruta or "señal"
    out = []
    if "$ref" in esq:
        return _comprobar(valor, _ref(esq["$ref"]), ruta)
    if "type" in esq:
        py = _TIPOS_JSON[esq["type"]]
        if not isinstance(valor, py) or (isinstance(valor, bool) and esq["type"] in ("integer", "number")):
            return ["%s: debe ser de tipo %s" % (donde, esq["type"])]
    if "const" in esq and (valor != esq["const"] or type(valor) is not type(esq["const"])):
        out.append("%s: debe ser %r" % (donde, esq["const"]))
    if "enum" in esq and valor not in esq["enum"]:
        out.append("%s: valor no admitido" % donde)
    if isinstance(valor, str):
        if "minLength" in esq and len(valor) < esq["minLength"]:
            out.append("%s: demasiado corto" % donde)
        if "maxLength" in esq and len(valor) > esq["maxLength"]:
            out.append("%s: demasiado largo" % donde)
        if "pattern" in esq and not re.search(esq["pattern"], valor):
            out.append("%s: formato no válido" % donde)
    if isinstance(valor, list):
        if "minItems" in esq and len(valor) < esq["minItems"]:
            out.append("%s: debe tener al menos %d elemento(s)" % (donde, esq["minItems"]))
        if "maxItems" in esq and len(valor) > esq["maxItems"]:
            out.append("%s: demasiados elementos" % donde)
        if "items" in esq:
            for i, v in enumerate(valor):
                out += _comprobar(v, esq["items"], "%s[%d]" % (ruta, i))
    if isinstance(valor, dict):
        for k in esq.get("required", ()):
            if k not in valor:
                out.append("%s: falta «%s»" % (donde, k))
        props = esq.get("properties", {})
        for k, v in valor.items():
            sub = "%s.%s" % (ruta, k) if ruta else k
            if k in props:
                out += _comprobar(v, props[k], sub)
            elif esq.get("additionalProperties") is False:
                out.append("%s: campo no permitido «%s»" % (donde, k))
    for sub in esq.get("allOf", ()):
        out += _comprobar(valor, sub, ruta)
    if "if" in esq and not _comprobar(valor, esq["if"], ruta) and "then" in esq:
        out += _comprobar(valor, esq["then"], ruta)
    if "not" in esq and not _comprobar(valor, esq["not"], ruta):
        out.append("%s: valor no admitido" % donde)
    return out


def _fecha(texto):
    try:
        d = datetime.fromisoformat(texto.replace("Z", "+00:00"))
    except (AttributeError, TypeError, ValueError):
        return None
    return d if d.tzinfo else None


def validar(senal):
    """Los problemas de una señal v0 como textos; lista vacía si es válida."""
    if not isinstance(senal, dict):
        return ["señal: debe ser un objeto JSON"]
    out = _comprobar(senal, SCHEMA, "")
    if out:
        return out
    primera = _fecha(senal["visto_por_primera_vez"])
    if primera is None:
        out.append("visto_por_primera_vez: fecha que no existe")
    if "visto_por_ultima_vez" in senal:
        ultima = _fecha(senal["visto_por_ultima_vez"])
        if ultima is None:
            out.append("visto_por_ultima_vez: fecha que no existe")
        elif primera and ultima < primera:
            out.append("visto_por_ultima_vez: es anterior a visto_por_primera_vez")
    return out


def main(argv):
    if len(argv) == 3 and argv[1] == "--hash-iban":
        print(hash_iban(argv[2]))
        return 0
    if len(argv) != 2:
        print(__doc__)
        return 2
    try:
        with open(argv[1], encoding="utf-8") as fh:
            datos = json.load(fh)
    except (OSError, ValueError) as e:
        print("No se pudo leer: %s" % e)
        return 2
    lista = datos["senales"] if isinstance(datos, dict) and "senales" in datos else datos if isinstance(datos, list) else [datos]
    problemas = ["[%d] %s" % (i, e) for i, s in enumerate(lista) for e in validar(s)]
    print("\n".join(problemas) if problemas else "%d señal(es) válida(s)" % len(lista))
    return 1 if problemas else 0


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