File size: 7,319 Bytes
3b01fc7
 
7fd88a5
3b01fc7
7fd88a5
 
 
 
 
 
3b01fc7
 
7fd88a5
 
 
 
 
3b01fc7
 
 
 
7fd88a5
3b01fc7
 
 
7fd88a5
 
3b01fc7
7fd88a5
3b01fc7
 
7fd88a5
 
 
 
 
 
 
 
 
3b01fc7
 
7fd88a5
 
 
 
 
 
 
 
3b01fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd88a5
 
 
 
3b01fc7
 
 
 
 
7fd88a5
3b01fc7
 
 
 
 
 
 
 
7fd88a5
3b01fc7
 
7fd88a5
 
 
 
 
 
3b01fc7
 
 
 
 
7fd88a5
 
3b01fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd88a5
 
 
 
 
 
 
 
 
3b01fc7
 
 
 
 
 
 
 
 
 
 
 
 
7fd88a5
 
3b01fc7
 
 
 
7fd88a5
 
 
3b01fc7
 
 
 
 
 
 
7fd88a5
3b01fc7
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#!/usr/bin/env python3
"""
validate_visado.py — Pre-Visa Document Validation (v16)
Agent: value.railnexus.io

Since v11 all rule/type/college data lives in ../data/*.json (SINGLE SOURCE OF TRUTH).
v16: agent_version is read from the package VERSION file (v15 still emitted 11.0.0).
This script is a CONFIG GENERATOR: it returns which checklist, rules, and
normativa the LLM must apply. Document parsing/validation is performed by
the agent (LLM) against this config — this script does NOT open documents.

Usage:
  python scripts/validate_visado.py --type valoracion_eco805 --colegio COAC --mode full
  python scripts/validate_visado.py --type proyecto_basico_ejecucion --colegio COAC --mode quick
  python scripts/validate_visado.py --type valoracion_eco805 --cee-severity advertencia

Output: JSON config -> {project config, checklist_file, rules, references_to_load}
"""

import argparse
import json
import os
import sys
from datetime import datetime

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from agent_version import AGENT_VERSION  # noqa: E402

DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")


def _load(name):
    path = os.path.join(DATA_DIR, name)
    if not os.path.exists(path):
        print(json.dumps({"valid": False,
                          "error": f"DATA FILE MISSING: data/{name}",
                          "fix": "restore data/ directory — single source of truth"}, ensure_ascii=False))
        sys.exit(2)
    with open(path, encoding="utf-8") as f:
        return json.load(f)


PROJECT_TYPES = _load("project_types.json")
ECM599_RULES = _load("ecm599_rules.json")
CONDICIONANTES = _load("condicionantes.json")
ADVERTENCIAS = _load("advertencias.json")
METODOS_MATRIX = _load("metodos_matrix.json")
QUICK_CHECK_ITEMS = _load("quick_check_items.json")
COMPROBACIONES_PREVIAS = _load("comprobaciones_previas.json")
COLLEGE_SPECIFICS = _load("colleges.json")


def get_college_requirements(colegio):
    if colegio and colegio.upper() in COLLEGE_SPECIFICS:
        return COLLEGE_SPECIFICS[colegio.upper()]
    return {"name": "CSCAE generico", "region": "Espana", "additional_requirements": [],
            "normativa_urbanistica": "Legislacion autonomica aplicable"}


def get_cte_dbs(project_type):
    db_map = {
        "anteproyecto": {},
        "proyecto_basico": {"DB-SE": "declaracion", "DB-SI": "justificacion", "DB-SUA": "declaracion",
                            "DB-HS": "declaracion", "DB-HR": "declaracion", "DB-HE": "declaracion"},
        "proyecto_basico_ejecucion": {db: "justificacion_detallada"
                                      for db in ["DB-SE", "DB-SI", "DB-SUA", "DB-HS", "DB-HR", "DB-HE"]},
        "legalizacion": {db: "comprobacion"
                         for db in ["DB-SE", "DB-SI", "DB-SUA", "DB-HS", "DB-HR", "DB-HE"]},
        "valoracion_eco805": {"DB-HE": "CEE_obligatorio"},
    }
    return db_map.get(project_type, {})


def generate_validation_config(project_type, colegio, mode, cee_severity):
    type_config = PROJECT_TYPES.get(project_type, {})
    college_config = get_college_requirements(colegio)
    is_tasacion = project_type == "valoracion_eco805"

    refs = [
        f"references/visado/checklists/{type_config.get('checklist_file', '')}",
        "references/visado/reparos/common-reparos.md",
        "references/visado/normativa/cte-dbs.md",
        "references/visado/normativa/loe.md",
    ]
    if is_tasacion:
        refs += ["references/visado/normativa/eco-805.md",
                 "references/visado/normativa/ecm-599-2025.md"]
    if project_type == "proyecto_basico_ejecucion":
        refs.append("references/visado/normativa/rd-164-2025-rsciei.md")
    if type_config.get("fiscalidad_promocion"):
        refs.append("references/countries/eu/spain/tax-law.md")
    if college_config.get("region") == "Catalunya":
        refs.append("references/visado/coac/coac-specifics.md")

    config = {
        "timestamp": datetime.now().isoformat(),
        "agent_version": AGENT_VERSION,
        "data_source": "data/*.json (single source of truth)",
        "project_type": project_type,
        "project_label": type_config.get("label", "Desconocido"),
        "check_mode": mode,
        "colegio": college_config["name"],
        "region": college_config["region"],
        "visado_obligatorio": type_config.get("visado_obligatorio", False),
        "checklist_file": f"references/visado/checklists/{type_config.get('checklist_file', '')}",
        "cte_justification_level": type_config.get("requires_cte_justification", False),
        "requires_ref_catastral": type_config.get("requires_ref_catastral", True),
        "presupuesto_level": type_config.get("presupuesto_level", "capitulos"),
        "requires_comunicacion_DO": type_config.get("requires_comunicacion_DO", False),
        "requires_ess": type_config.get("requires_ess", False),
        "requires_geotecnico": type_config.get("requires_geotecnico", False),
        "college_additional_requirements": college_config["additional_requirements"],
        "normativa_urbanistica_autonomica": college_config.get("normativa_urbanistica", ""),
        "references_to_load": refs,
        "cte_dbs_applicable": get_cte_dbs(project_type),
    }

    if is_tasacion:
        # v11: ECM-CEE-03 configurable severity — mechanism implemented
        rules = json.loads(json.dumps(ECM599_RULES))  # deep copy
        for r in rules:
            if r.get("id") == "ECM-CEE-03":
                r["severidad"] = cee_severity.upper()
                r["nota"] = f"Configurado por sociedad via --cee-severity={cee_severity}"
        config["ecm599_rules"] = rules
        config["ecm599_rules_count"] = len(rules)
        config["cee_severity_config"] = cee_severity.upper()
        config["condicionantes_art10_11"] = CONDICIONANTES
        config["advertencias_art12_13"] = ADVERTENCIAS
        config["comprobaciones_previas_art7_9"] = COMPROBACIONES_PREVIAS
        config["metodos_matrix"] = METODOS_MATRIX
        config["normativa_aplicada"] = "ECO/805/2003 consolidada con ECM/599/2025 (vigor 12/08/2025)"

    if mode == "quick":
        config["quick_check_items"] = QUICK_CHECK_ITEMS

    return config


def main():
    parser = argparse.ArgumentParser(
        description=f"Pre-Visa Document Validation v{AGENT_VERSION} (config generator)")
    parser.add_argument("--type", required=True, help="Project type")
    parser.add_argument("--jurisdiction", default="spain")
    parser.add_argument("--colegio", default="COAC")
    parser.add_argument("--mode", default="full", choices=["quick", "full"])
    parser.add_argument("--cee-severity", default="bloqueante",
                        choices=["bloqueante", "advertencia"],
                        help="ECM-CEE-03: severidad de CEE ausente, configurable por sociedad")
    args = parser.parse_args()

    if args.type not in PROJECT_TYPES:
        print(json.dumps({"valid": False, "error": f"Tipo no reconocido: {args.type}",
                          "valid_types": list(PROJECT_TYPES.keys())}, indent=2, ensure_ascii=False))
        sys.exit(1)

    config = generate_validation_config(args.type, args.colegio, args.mode, args.cee_severity)
    print(json.dumps(config, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()