"""Valida forma e imutabilidade; não comprova validade fiscal."""
import json
from pathlib import Path

from acbr import AcbrError, Documento, describe_field, validate_document
from acbr.models import TNFe

FIXTURE = Path(__file__).with_name("documento_homologacao.json")


def carregar_documento() -> Documento:
    dados: TNFe = json.loads(FIXTURE.read_text(encoding="utf-8"))
    assert dados["Ide"]["tpAmb"] == "taHomologacao"
    return Documento(validate_document(dados))


def main() -> int:
    documento = carregar_documento()
    copia = documento.to_wire()
    copia["Ide"]["modelo"] = 65
    assert documento.to_wire()["Ide"]["modelo"] == 55
    campo = describe_field("Det[].Prod.vProd")
    assert campo["kind"] == "decimal"
    assert campo["inputType"] == "string"
    try:
        Documento({"Det": [{"Prod": {"vProd": 10.0}}]})
    except AcbrError as erro:
        assert erro.codigo == "DECIMAL_INVALIDO"
    else:
        raise AssertionError("O contrato deveria rejeitar float no decimal.")
    print(json.dumps({
        "contrato_estrutural": "OK",
        "ambiente": "HOMOLOGACAO",
        "dados": "SINTETICOS; NAO TRANSMITIR",
        "sourceRevision": campo["sourceRevision"],
    }, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
