bonita2026 commited on
Commit
3b01fc7
·
verified ·
1 Parent(s): 585a29e

Upload 7 files

Browse files
scripts/validate_dscr.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ validate_dscr.py — Calculates DSCR and returns GREEN/YELLOW/RED with jurisdiction-calibrated thresholds.
4
+
5
+ Usage:
6
+ python scripts/validate_dscr.py --noi 850000 --debt_service 620000 --jurisdiction uk
7
+ python scripts/validate_dscr.py --noi 1200000 --debt_service 850000 --jurisdiction usa --asset_type commercial
8
+
9
+ Output:
10
+ JSON with DSCR value, applicable threshold, margin, and RED/YELLOW/GREEN status.
11
+
12
+ Sources for thresholds: typical institutional lender requirements by market.
13
+ These are reference ranges — actual lender requirements vary. Verify with specific lender.
14
+ """
15
+
16
+ import argparse
17
+ import json
18
+ import sys
19
+
20
+ # ─── DSCR Thresholds by Jurisdiction and Asset Type ──────────────────────────
21
+ # Format: min_normal = minimum for GREEN; min_stress = minimum for YELLOW
22
+ # Below min_stress = RED (escalate immediately)
23
+
24
+ THRESHOLDS = {
25
+ # ── USA ──────────────────────────────────────────────────────────────────
26
+ "usa_commercial": {
27
+ "min_normal": 1.25,
28
+ "min_stress": 1.10,
29
+ "note": "US CRE institutional lender standard (CMBS/life company)",
30
+ "source": "Typical US commercial real estate lending",
31
+ },
32
+ "usa_residential": {
33
+ "min_normal": 1.20,
34
+ "min_stress": 1.05,
35
+ "note": "US residential rental / multifamily",
36
+ "source": "Fannie Mae / Freddie Mac multifamily guidelines",
37
+ },
38
+ "usa_industrial": {
39
+ "min_normal": 1.25,
40
+ "min_stress": 1.10,
41
+ "note": "US industrial / logistics",
42
+ "source": "Typical US industrial lending",
43
+ },
44
+
45
+ # ── UK ───────────────────────────────────────────────────────────────────
46
+ "uk_commercial": {
47
+ "min_normal": 1.20,
48
+ "min_stress": 1.05,
49
+ "note": "UK CRE standard (clearing banks / debt funds)",
50
+ "source": "Typical UK commercial real estate lending",
51
+ },
52
+ "uk_residential": {
53
+ "min_normal": 1.25,
54
+ "min_stress": 1.10,
55
+ "note": "UK buy-to-let / PRS residential",
56
+ "source": "UK PRA / typical BTL lender requirement",
57
+ },
58
+ "uk_industrial": {
59
+ "min_normal": 1.20,
60
+ "min_stress": 1.05,
61
+ "note": "UK logistics / industrial",
62
+ "source": "Typical UK industrial lending",
63
+ },
64
+
65
+ # ── SPAIN ─────────────────────────────────────────────────────────────────
66
+ "spain_commercial": {
67
+ "min_normal": 1.25,
68
+ "min_stress": 1.10,
69
+ "note": "Spain CRE (banca española / European debt funds)",
70
+ "source": "Typical Spain commercial real estate lending",
71
+ },
72
+ "spain_residential": {
73
+ "min_normal": 1.20,
74
+ "min_stress": 1.05,
75
+ "note": "Spain residential rental",
76
+ "source": "Typical Spain residential lending",
77
+ },
78
+ "spain_industrial": {
79
+ "min_normal": 1.25,
80
+ "min_stress": 1.10,
81
+ "note": "Spain industrial / logistics",
82
+ "source": "Typical Spain industrial lending",
83
+ },
84
+
85
+ # ── GERMANY ───────────────────────────────────────────────────────────────
86
+ "germany_commercial": {
87
+ "min_normal": 1.20,
88
+ "min_stress": 1.05,
89
+ "note": "Germany CRE (Pfandbrief-eligible lender standard)",
90
+ "source": "Germany Pfandbrief bank / typical CRE lending",
91
+ },
92
+ "germany_residential": {
93
+ "min_normal": 1.20,
94
+ "min_stress": 1.05,
95
+ "note": "Germany residential rental (Wohnimmobilien)",
96
+ "source": "Typical German residential lending",
97
+ },
98
+
99
+ # ── FRANCE ────────────────────────────────────────────────────────────────
100
+ "france_commercial": {
101
+ "min_normal": 1.20,
102
+ "min_stress": 1.05,
103
+ "note": "France CRE",
104
+ "source": "Typical France commercial real estate lending",
105
+ },
106
+
107
+ # ── INDIA ─────────────────────────────────────────────────────────────────
108
+ "india_commercial": {
109
+ "min_normal": 1.35,
110
+ "min_stress": 1.15,
111
+ "note": "India CRE (aligned with RBI guidelines for CRE lending)",
112
+ "source": "RBI CRE lending guidelines / typical Indian bank standard",
113
+ },
114
+ "india_residential": {
115
+ "min_normal": 1.30,
116
+ "min_stress": 1.10,
117
+ "note": "India residential / housing finance",
118
+ "source": "NHB / typical Indian housing finance company",
119
+ },
120
+
121
+ # ── UAE ───────────────────────────────────────────────────────────────────
122
+ "uae_commercial": {
123
+ "min_normal": 1.25,
124
+ "min_stress": 1.10,
125
+ "note": "UAE CRE (local and international bank standard)",
126
+ "source": "Typical UAE commercial real estate lending",
127
+ },
128
+ "uae_residential": {
129
+ "min_normal": 1.25,
130
+ "min_stress": 1.10,
131
+ "note": "UAE residential",
132
+ "source": "UAE Central Bank mortgage regulations",
133
+ },
134
+
135
+ # ── INFRASTRUCTURE ────────────────────────────────────────────────────────
136
+ "infrastructure": {
137
+ "min_normal": 1.40,
138
+ "min_stress": 1.20,
139
+ "note": "Infrastructure / project finance (PPP / concession standard)",
140
+ "source": "MDB / project finance lender standard",
141
+ },
142
+ "infrastructure_social": {
143
+ "min_normal": 1.30,
144
+ "min_stress": 1.15,
145
+ "note": "Social infrastructure (hospitals, schools, availability-based)",
146
+ "source": "Typical social infrastructure project finance",
147
+ },
148
+
149
+ # ── DEFAULT ───────────────────────────────────────────────────────────────
150
+ "default": {
151
+ "min_normal": 1.25,
152
+ "min_stress": 1.10,
153
+ "note": "Industry default (jurisdiction not specified or not recognized)",
154
+ "source": "General industry reference",
155
+ },
156
+ }
157
+
158
+ # ─── Helper: Resolve threshold key ────────────────────────────────────────────
159
+
160
+ def resolve_key(jurisdiction: str, asset_type: str) -> str:
161
+ """Return the best matching threshold key."""
162
+ # Direct match
163
+ key = f"{jurisdiction}_{asset_type}"
164
+ if key in THRESHOLDS:
165
+ return key
166
+ # Infrastructure shortcut
167
+ if asset_type in ("infrastructure", "infrastructure_social"):
168
+ return asset_type if asset_type in THRESHOLDS else "infrastructure"
169
+ # Jurisdiction + commercial fallback
170
+ key_commercial = f"{jurisdiction}_commercial"
171
+ if key_commercial in THRESHOLDS:
172
+ return key_commercial
173
+ return "default"
174
+
175
+
176
+ # ─── Core Calculation ──────────────────────────────────────────────────────────
177
+
178
+ def evaluate_dscr(
179
+ noi: float,
180
+ debt_service: float,
181
+ jurisdiction: str = "default",
182
+ asset_type: str = "commercial",
183
+ ) -> dict:
184
+ if debt_service <= 0:
185
+ return {"error": "debt_service must be greater than 0"}
186
+ if noi < 0:
187
+ return {"error": "NOI is negative — property is loss-making. DSCR not meaningful."}
188
+
189
+ dscr = noi / debt_service
190
+ thr_key = resolve_key(jurisdiction, asset_type)
191
+ thr = THRESHOLDS[thr_key]
192
+
193
+ margin_vs_normal = dscr - thr["min_normal"]
194
+ margin_vs_stress = dscr - thr["min_stress"]
195
+
196
+ # Status determination
197
+ if dscr >= thr["min_normal"]:
198
+ status = "GREEN"
199
+ status_detail = (
200
+ f"DSCR {dscr:.2f}x exceeds minimum normal threshold of {thr['min_normal']:.2f}x "
201
+ f"by {margin_vs_normal:+.2f}x. Adequate debt service coverage."
202
+ )
203
+ elif dscr >= thr["min_stress"]:
204
+ status = "YELLOW"
205
+ status_detail = (
206
+ f"DSCR {dscr:.2f}x is below normal minimum ({thr['min_normal']:.2f}x) "
207
+ f"but above stress minimum ({thr['min_stress']:.2f}x). "
208
+ f"Marginal coverage — review cash flow assumptions and sensitivity."
209
+ )
210
+ else:
211
+ status = "RED"
212
+ status_detail = (
213
+ f"DSCR {dscr:.2f}x is below stress minimum of {thr['min_stress']:.2f}x. "
214
+ f"Debt service coverage is INSUFFICIENT even under stress threshold. "
215
+ f"ESCALATE — do not proceed without restructuring debt or improving NOI."
216
+ )
217
+
218
+ # Breakeven calculation
219
+ breakeven_noi = debt_service * thr["min_normal"]
220
+ noi_gap = breakeven_noi - noi
221
+
222
+ return {
223
+ "inputs": {
224
+ "noi": noi,
225
+ "debt_service": debt_service,
226
+ "jurisdiction": jurisdiction,
227
+ "asset_type": asset_type,
228
+ },
229
+ "result": {
230
+ "dscr": round(dscr, 3),
231
+ "dscr_formatted": f"{dscr:.2f}x",
232
+ },
233
+ "threshold_applied": {
234
+ "key": thr_key,
235
+ "min_normal": thr["min_normal"],
236
+ "min_stress": thr["min_stress"],
237
+ "note": thr["note"],
238
+ "source": thr["source"],
239
+ },
240
+ "margins": {
241
+ "vs_normal_threshold": f"{margin_vs_normal:+.3f}x",
242
+ "vs_stress_threshold": f"{margin_vs_stress:+.3f}x",
243
+ },
244
+ "breakeven": {
245
+ "noi_required_for_green": round(breakeven_noi, 0),
246
+ "noi_gap_to_green": round(noi_gap, 0),
247
+ "noi_gap_pct": f"{(noi_gap / breakeven_noi * 100):.1f}%" if noi_gap > 0 else "0.0% — already GREEN",
248
+ },
249
+ "status": status,
250
+ "status_detail": status_detail,
251
+ "escalation_required": status == "RED",
252
+ }
253
+
254
+
255
+ # ─── CLI ──────────────────────────────────────────────────────────────────────
256
+
257
+ def main():
258
+ parser = argparse.ArgumentParser(
259
+ description="Calculate DSCR with jurisdiction-calibrated thresholds."
260
+ )
261
+ parser.add_argument("--noi", type=float, required=True, help="Annual Net Operating Income")
262
+ parser.add_argument("--debt_service", type=float, required=True, help="Annual debt service (P&I or IO)")
263
+ parser.add_argument(
264
+ "--jurisdiction",
265
+ default="default",
266
+ choices=["usa", "uk", "spain", "germany", "france", "india", "uae", "singapore", "default"],
267
+ help="Country/jurisdiction of the property (default: default)",
268
+ )
269
+ parser.add_argument(
270
+ "--asset_type",
271
+ default="commercial",
272
+ choices=["commercial", "residential", "industrial", "infrastructure", "infrastructure_social", "mixed"],
273
+ help="Asset type (default: commercial)",
274
+ )
275
+ args = parser.parse_args()
276
+
277
+ result = evaluate_dscr(args.noi, args.debt_service, args.jurisdiction, args.asset_type)
278
+ print(json.dumps(result, indent=2, ensure_ascii=False))
279
+
280
+
281
+ if __name__ == "__main__":
282
+ main()
scripts/validate_jurisdiction.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ validate_jurisdiction.py — Detects jurisdiction and returns the applicable legal framework.
4
+
5
+ Usage:
6
+ python scripts/validate_jurisdiction.py --input "Madrid, Spain" [--type commercial]
7
+
8
+ Output:
9
+ JSON with country, currency, applicable legal references, thresholds, and
10
+ instructions for loading the correct country reference files.
11
+
12
+ Run this FIRST before any fiscal or legal analysis.
13
+ """
14
+
15
+ import argparse
16
+ import json
17
+ import sys
18
+
19
+ # ─── Jurisdiction Framework Map ────────────────────────────────────────────────
20
+
21
+ JURISDICTION_MAP = {
22
+ "spain": {
23
+ "country": "spain",
24
+ "country_name": "Spain / España",
25
+ "currency": "EUR",
26
+ "currency_symbol": "€",
27
+ "stamp_duty_type": "ITP/AJD (resale) or IVA+AJD (new build)",
28
+ "tax_ref": "references/countries/eu/spain/tax-law.md",
29
+ "zoning_ref": "references/countries/eu/spain/zoning-law.md",
30
+ "lease_ref": "references/countries/eu/spain/lease-law.md",
31
+ "lease_law_primary": "LAU 2013 (Ley de Arrendamientos Urbanos) / LAE",
32
+ "zoning_law_primary": "Ley del Suelo RDL 7/2015 / PGOU municipal",
33
+ "financial_reporting_default": "PGC / NIIF-UE (IFRS adopted)",
34
+ "high_value_threshold": 1_000_000,
35
+ "high_value_currency": "EUR",
36
+ "non_resident_withholding_rate": 0.03,
37
+ "non_resident_withholding_note": (
38
+ "Buyer MUST withhold 3% of sale price and remit via Modelo 211 "
39
+ "within 30 days of deed (IRNR Art.25.2 LIRNR). "
40
+ "Buyer is jointly liable if not withheld."
41
+ ),
42
+ "tax_authority": "AEAT (Agencia Estatal de Administración Tributaria)",
43
+ "land_registry": "Registro de la Propiedad",
44
+ "analysis_label": "Analysis under Spanish law",
45
+ "key_watch_points": [
46
+ "Check ITP vs IVA: resale = ITP; new build = IVA+AJD (mutually exclusive)",
47
+ "Calculate Plusvalía municipal (IIVTNU) by BOTH methods (STC TC 26/2021)",
48
+ "If seller is non-resident: configure 3% withholding by buyer",
49
+ "Verify valor de referencia catastral vs transaction price",
50
+ "Check CCAA-specific ITP rate (Madrid 6%, Cataluña 10%, Baleares 11%)",
51
+ ],
52
+ },
53
+
54
+ "uk": {
55
+ "country": "uk",
56
+ "country_name": "United Kingdom",
57
+ "currency": "GBP",
58
+ "currency_symbol": "£",
59
+ "stamp_duty_type": "SDLT (England/NI) / LBTT (Scotland) / LTT (Wales)",
60
+ "tax_ref": "references/countries/uk/tax-law.md",
61
+ "zoning_ref": "references/countries/uk/zoning-law.md",
62
+ "lease_ref": "references/countries/uk/lease-law.md",
63
+ "lease_law_primary": "Landlord and Tenant Act 1954 / Law of Property Act 1925",
64
+ "zoning_law_primary": "Town and Country Planning Act 1990 / NPPF 2023",
65
+ "financial_reporting_default": "IFRS (listed) / FRS102 (SME)",
66
+ "high_value_threshold": 750_000,
67
+ "high_value_currency": "GBP",
68
+ "non_resident_withholding_rate": None,
69
+ "non_resident_withholding_note": (
70
+ "No FIRPTA-style withholding on sale. Non-resident buyer SDLT surcharge +2%. "
71
+ "CGT on UK residential must be reported and paid within 60 days of completion."
72
+ ),
73
+ "tax_authority": "HMRC",
74
+ "land_registry": "HM Land Registry",
75
+ "analysis_label": "Analysis under UK law",
76
+ "key_watch_points": [
77
+ "SDLT return MUST be filed within 14 days of completion (SDLT Act 2003 s.76)",
78
+ "CGT on residential property: report and pay within 60 days via HMRC UK Property account",
79
+ "Check if lease is inside or outside LTA 1954 (security of tenure)",
80
+ "Check for ATED if company holds residential property > GBP 500K",
81
+ "Check Option to Tax (OTT) status for VAT on commercial property",
82
+ "Non-resident buyer SDLT surcharge: +2% on each band",
83
+ ],
84
+ },
85
+
86
+ "usa": {
87
+ "country": "usa",
88
+ "country_name": "United States of America",
89
+ "currency": "USD",
90
+ "currency_symbol": "$",
91
+ "stamp_duty_type": "State Transfer Tax (rate varies by state; 0% Texas to 4%+ NY)",
92
+ "tax_ref": "references/countries/usa/tax-law.md",
93
+ "zoning_ref": "references/countries/usa/zoning-law.md",
94
+ "lease_ref": "references/countries/usa/lease-law.md",
95
+ "lease_law_primary": "State landlord-tenant statutes / UCC",
96
+ "zoning_law_primary": "Municipal zoning ordinances / state enabling statutes",
97
+ "financial_reporting_default": "US GAAP (ASC 842 leases, ASC 805 business combinations)",
98
+ "high_value_threshold": 1_000_000,
99
+ "high_value_currency": "USD",
100
+ "non_resident_withholding_rate": 0.15,
101
+ "non_resident_withholding_note": (
102
+ "FIRPTA: buyer withholds 15% of AMOUNT REALIZED (not gain) from foreign seller. "
103
+ "File Form 8288 within 20 days of closing. "
104
+ "Exception: price ≤ USD 300K + buyer residence use = 0%."
105
+ ),
106
+ "tax_authority": "IRS (federal) + State revenue departments",
107
+ "land_registry": "County Recorder / Register of Deeds",
108
+ "analysis_label": "Analysis under US law",
109
+ "key_watch_points": [
110
+ "1031 exchange: 45-day ID window and 180-day closing window are ABSOLUTE",
111
+ "Qualified Intermediary (QI) mandatory for 1031 — seller cannot touch funds",
112
+ "FIRPTA: buyer withholds 15% if seller is foreign person",
113
+ "Depreciation recapture (Sec.1250) taxed at max 25% — separate from LTCG rate",
114
+ "State transfer tax rate varies widely — verify specific state and county",
115
+ "NIIT 3.8% surtax if MAGI exceeds threshold",
116
+ ],
117
+ },
118
+
119
+ "france": {
120
+ "country": "france",
121
+ "country_name": "France",
122
+ "currency": "EUR",
123
+ "currency_symbol": "€",
124
+ "stamp_duty_type": "Droits de mutation (~5.8%) or TVA (new build)",
125
+ "tax_ref": "references/countries/eu/france/tax-law.md",
126
+ "zoning_ref": "references/countries/eu/france/tax-law.md",
127
+ "lease_ref": "references/countries/eu/france/tax-law.md",
128
+ "lease_law_primary": "Bail commercial (Décret 1953 / Loi Pinel 2014) — 3-6-9 structure",
129
+ "zoning_law_primary": "Plan Local d'Urbanisme (PLU) / Code de l'Urbanisme",
130
+ "financial_reporting_default": "PCG / IFRS",
131
+ "high_value_threshold": 1_000_000,
132
+ "high_value_currency": "EUR",
133
+ "non_resident_withholding_rate": None,
134
+ "non_resident_withholding_note": (
135
+ "Non-EU residents: 26.5% CGT rate (vs 36.2% for residents). "
136
+ "No withholding on purchase price."
137
+ ),
138
+ "tax_authority": "Direction Générale des Finances Publiques (DGFiP)",
139
+ "land_registry": "Service de la publicité foncière / Cadastre",
140
+ "analysis_label": "Analyse sous droit français",
141
+ "key_watch_points": [
142
+ "Bail commercial: minimum 9 years; tenant can exit every 3 years with 6 months notice",
143
+ "Droits de mutation ~5.8% for resale; TVA 20% for new build",
144
+ "Plus-value: 36.2% total (19% + 17.2% social); exempt after 22 years (income) / 30 years (social)",
145
+ "Principal residence always exempt from plus-value",
146
+ "Rent indexation: ILC (shops) or ILAT (offices/logistics) — quarterly INSEE index",
147
+ ],
148
+ },
149
+
150
+ "germany": {
151
+ "country": "germany",
152
+ "country_name": "Germany / Deutschland",
153
+ "currency": "EUR",
154
+ "currency_symbol": "€",
155
+ "stamp_duty_type": "Grunderwerbsteuer (GrESt) 3.5–6.5% depending on Bundesland",
156
+ "tax_ref": "references/countries/eu/germany/tax-law.md",
157
+ "zoning_ref": "references/countries/eu/germany/tax-law.md",
158
+ "lease_ref": "references/countries/eu/germany/tax-law.md",
159
+ "lease_law_primary": "BGB (Bürgerliches Gesetzbuch) / Gewerberaummiete",
160
+ "zoning_law_primary": "BauGB / BauNVO / Bebauungsplan",
161
+ "financial_reporting_default": "HGB / IFRS",
162
+ "high_value_threshold": 1_000_000,
163
+ "high_value_currency": "EUR",
164
+ "non_resident_withholding_rate": None,
165
+ "non_resident_withholding_note": (
166
+ "Same tax rules as residents. No withholding on sale price. "
167
+ "Capital gains: exempt if held >10 years (individuals). "
168
+ "Companies: no 10-year exemption."
169
+ ),
170
+ "tax_authority": "Finanzamt (local tax office)",
171
+ "land_registry": "Grundbuch (Land Register)",
172
+ "analysis_label": "Analyse nach deutschem Recht",
173
+ "key_watch_points": [
174
+ "GrESt rate varies by Bundesland: Bavaria 3.5% (lowest) to Brandenburg/NRW/Saarland 6.5%",
175
+ "Spekulationssteuer: gains on property held <10 years taxed as income (individuals)",
176
+ "Share deal threshold: 90% ownership triggers GrESt (post-2021 reform)",
177
+ "Grundsteuer reform 2025: new calculation method — verify current municipal rates",
178
+ "Commercial rents: exempt from VAT unless landlord opts in (Optionserklärung)",
179
+ ],
180
+ },
181
+
182
+ "india": {
183
+ "country": "india",
184
+ "country_name": "India",
185
+ "currency": "INR",
186
+ "currency_symbol": "₹",
187
+ "stamp_duty_type": "Stamp Duty (state-specific, 4–8%) + Registration fee",
188
+ "tax_ref": "references/countries/india/tax-law.md",
189
+ "zoning_ref": "references/countries/india/tax-law.md",
190
+ "lease_ref": "references/countries/india/tax-law.md",
191
+ "lease_law_primary": "Transfer of Property Act 1882 / State Rent Control Acts / RERA 2016",
192
+ "zoning_law_primary": "Master Plans / Development Control Rules / RERA",
193
+ "financial_reporting_default": "Ind AS / IGAAP",
194
+ "high_value_threshold": 50_000_000, # 5 crore
195
+ "high_value_currency": "INR",
196
+ "non_resident_withholding_rate": None,
197
+ "non_resident_withholding_note": (
198
+ "Sec.195 TDS: rate per applicable DTAA; without DTAA: 20%. "
199
+ "FEMA: NRI/OCI can purchase residential/commercial (not agricultural). "
200
+ "Repatriation subject to FEMA conditions."
201
+ ),
202
+ "tax_authority": "Income Tax Department / CBDT / GST Council",
203
+ "land_registry": "Sub-Registrar Office (state-wise)",
204
+ "analysis_label": "Analysis under Indian law",
205
+ "key_watch_points": [
206
+ "Section 50C: if circle rate > sale price, capital gains computed on circle rate",
207
+ "Section 56(2)(x): buyer taxed on shortfall vs circle rate if diff > ₹50K",
208
+ "TDS 194-IA: buyer deducts 1% if consideration > ₹50 lakhs (Form 26QB)",
209
+ "GST 5% on under-construction residential; nil on completed (post-OC)",
210
+ "RERA: check registration and compliance before any developer transaction",
211
+ "FEMA: verify NRI/foreign entity eligibility before acquisition",
212
+ ],
213
+ },
214
+
215
+ "uae": {
216
+ "country": "uae",
217
+ "country_name": "United Arab Emirates",
218
+ "currency": "AED",
219
+ "currency_symbol": "AED",
220
+ "stamp_duty_type": "DLD Transfer Fee 4% (Dubai Land Department)",
221
+ "tax_ref": "references/countries/uae/tax-law.md",
222
+ "zoning_ref": "references/countries/uae/tax-law.md",
223
+ "lease_ref": "references/countries/uae/tax-law.md",
224
+ "lease_law_primary": "UAE Tenancy Law Federal / Dubai Law 26/2007 (as amended)",
225
+ "zoning_law_primary": "Dubai Master Plan / Abu Dhabi Urban Planning Council",
226
+ "financial_reporting_default": "IFRS",
227
+ "high_value_threshold": 4_000_000,
228
+ "high_value_currency": "AED",
229
+ "non_resident_withholding_rate": None,
230
+ "non_resident_withholding_note": (
231
+ "No capital gains tax, no income tax, no withholding on sale proceeds. "
232
+ "Foreigners restricted to freehold zones only. VAT 5% on commercial leases."
233
+ ),
234
+ "tax_authority": "Federal Tax Authority (FTA) for VAT",
235
+ "land_registry": "Dubai Land Department (DLD) / ADNOC for Abu Dhabi",
236
+ "analysis_label": "Analysis under UAE law",
237
+ "key_watch_points": [
238
+ "Foreign buyers: restricted to designated freehold zones only",
239
+ "DLD transfer fee 4%: typically split 2% buyer / 2% seller",
240
+ "Ejari registration mandatory for all tenancy contracts in Dubai",
241
+ "RERA rent calculator governs permissible rent increases in Dubai",
242
+ "No capital gains tax; no income tax on individuals in UAE",
243
+ "VAT 5% applies to commercial lease rentals; residential exempt",
244
+ ],
245
+ },
246
+
247
+ "singapore": {
248
+ "country": "singapore",
249
+ "country_name": "Singapore",
250
+ "currency": "SGD",
251
+ "currency_symbol": "S$",
252
+ "stamp_duty_type": "BSD (Buyer's Stamp Duty) + ABSD (Additional BSD for foreigners)",
253
+ "tax_ref": "references/countries/singapore/tax-law.md",
254
+ "zoning_ref": "references/countries/singapore/tax-law.md",
255
+ "lease_ref": "references/countries/singapore/tax-law.md",
256
+ "lease_law_primary": "Conveyancing and Law of Property Act / Common law",
257
+ "zoning_law_primary": "Urban Redevelopment Authority (URA) Master Plan",
258
+ "financial_reporting_default": "SFRS (aligned with IFRS)",
259
+ "high_value_threshold": 1_500_000,
260
+ "high_value_currency": "SGD",
261
+ "non_resident_withholding_rate": None,
262
+ "non_resident_withholding_note": (
263
+ "ABSD: foreigners pay 60% ABSD on residential (as of 2023). "
264
+ "No capital gains tax in Singapore. No withholding on sale proceeds."
265
+ ),
266
+ "tax_authority": "Inland Revenue Authority of Singapore (IRAS)",
267
+ "land_registry": "Singapore Land Authority (SLA)",
268
+ "analysis_label": "Analysis under Singapore law",
269
+ "key_watch_points": [
270
+ "ABSD for foreign buyers: 60% on residential (verify current rate — changes frequently)",
271
+ "BSD: 1-6% progressive on purchase price",
272
+ "No capital gains tax; no withholding tax on property sale",
273
+ "99-year leasehold is standard for most properties; freehold rare",
274
+ "URA Master Plan governs land use — check gross plot ratio (GPR)",
275
+ ],
276
+ },
277
+ }
278
+
279
+ # ─── Keyword Detection ────────────────────────────────────────────────────────
280
+
281
+ KEYWORDS = {
282
+ "spain": [
283
+ "spain", "españa", "espana", "spanish", "madrid", "barcelona", "sevilla",
284
+ "valencia", "bilbao", "zaragoza", "malaga", "alicante", "marbella",
285
+ "ITP", "AJD", "plusvalia", "IRNR", "catastro", "PGOU", "ayuntamiento",
286
+ "registro propiedad", "notario", "escritura", "CCAA", "comunidad autonoma",
287
+ ],
288
+ "uk": [
289
+ "uk", "united kingdom", "england", "scotland", "wales", "northern ireland",
290
+ "london", "manchester", "birmingham", "edinburgh", "cardiff", "glasgow",
291
+ "GBP", "sterling", "pound", "SDLT", "LTA", "NPPF", "RICS", "leasehold",
292
+ "freehold", "planning permission", "section 106", "land registry", "HMRC",
293
+ "break clause uk", "dilapidations", "service charge", "ATED",
294
+ ],
295
+ "usa": [
296
+ "usa", "united states", "america", "us real estate", "california", "new york",
297
+ "texas", "florida", "illinois", "massachusetts", "new jersey", "washington",
298
+ "USD", "dollar", "1031", "FIRPTA", "REIT", "cap rate usa", "NNN lease",
299
+ "CAM charges", "CMBS", "zoning ordinance", "HOA", "escrow usa",
300
+ ],
301
+ "france": [
302
+ "france", "french", "paris", "lyon", "marseille", "bordeaux", "toulouse",
303
+ "nice", "nantes", "PLU", "bail commercial", "TVA immobilier", "droits de mutation",
304
+ "cadastre", "notaire france", "plus-value", "DGFiP",
305
+ ],
306
+ "germany": [
307
+ "germany", "deutschland", "german", "berlin", "munich", "münchen", "hamburg",
308
+ "frankfurt", "cologne", "köln", "düsseldorf", "stuttgart",
309
+ "GrESt", "Grunderwerbsteuer", "BauGB", "Bebauungsplan", "Grundbuch",
310
+ "Finanzamt", "Mietrecht", "Gewerberaum",
311
+ ],
312
+ "india": [
313
+ "india", "indian", "mumbai", "delhi", "bangalore", "bengaluru", "chennai",
314
+ "hyderabad", "pune", "kolkata", "ahmedabad", "INR", "rupee", "crore", "lakh",
315
+ "RERA", "TDS property", "stamp duty india", "GST property", "circle rate",
316
+ "ready reckoner", "khata", "7/12", "CERSAI", "OC certificate india",
317
+ ],
318
+ "uae": [
319
+ "uae", "dubai", "abu dhabi", "sharjah", "ajman", "ras al khaimah",
320
+ "AED", "dirham", "DIFC", "DLD", "freehold zone", "Ejari", "RERA dubai",
321
+ "Strata Law", "ADNOC", "SPA dubai",
322
+ ],
323
+ "singapore": [
324
+ "singapore", "SGD", "singdollar", "URA", "HDB", "ABSD", "BSD",
325
+ "master plan singapore", "plot ratio", "gross floor area singapore",
326
+ "99-year leasehold", "IRAS",
327
+ ],
328
+ }
329
+
330
+ # ─── Core Functions ────────────────────────────────────────────────────────────
331
+
332
+ def detect_jurisdiction(text: str) -> dict | None:
333
+ """Score each jurisdiction by keyword matches; return highest-scoring one."""
334
+ text_lower = text.lower()
335
+ scores = {}
336
+ for jur, kws in KEYWORDS.items():
337
+ score = sum(1 for k in kws if k.lower() in text_lower)
338
+ if score > 0:
339
+ scores[jur] = score
340
+ if not scores:
341
+ return None
342
+ best = max(scores, key=scores.get)
343
+ return JURISDICTION_MAP[best]
344
+
345
+
346
+ def build_output(framework: dict, asset_type: str) -> dict:
347
+ """Build the full output object."""
348
+ return {
349
+ "jurisdiction_detected": framework["country"],
350
+ "country_name": framework["country_name"],
351
+ "currency": framework["currency"],
352
+ "currency_symbol": framework["currency_symbol"],
353
+ "asset_type": asset_type,
354
+ "analysis_label": framework["analysis_label"],
355
+ "stamp_duty_type": framework["stamp_duty_type"],
356
+ "references_to_load": {
357
+ "tax": framework["tax_ref"],
358
+ "zoning": framework["zoning_ref"],
359
+ "lease": framework["lease_ref"],
360
+ },
361
+ "applicable_law": {
362
+ "lease": framework["lease_law_primary"],
363
+ "zoning": framework["zoning_law_primary"],
364
+ "financial_reporting": framework["financial_reporting_default"],
365
+ },
366
+ "thresholds": {
367
+ "high_value": framework["high_value_threshold"],
368
+ "high_value_currency": framework["high_value_currency"],
369
+ "non_resident_withholding_rate": framework["non_resident_withholding_rate"],
370
+ },
371
+ "non_resident_withholding_note": framework["non_resident_withholding_note"],
372
+ "tax_authority": framework["tax_authority"],
373
+ "land_registry": framework["land_registry"],
374
+ "key_watch_points": framework["key_watch_points"],
375
+ "instruction": (
376
+ f"Load {framework['tax_ref']} before citing any tax statute. "
377
+ f"Label all output: '{framework['analysis_label']} as of [DATE]'."
378
+ ),
379
+ }
380
+
381
+
382
+ def main():
383
+ parser = argparse.ArgumentParser(
384
+ description="Detect real estate jurisdiction and return applicable legal framework."
385
+ )
386
+ parser.add_argument(
387
+ "--input",
388
+ required=True,
389
+ help="Property details, address, or description (e.g. 'Office building in Madrid, Spain')",
390
+ )
391
+ parser.add_argument(
392
+ "--type",
393
+ dest="asset_type",
394
+ default="commercial",
395
+ choices=["residential", "commercial", "industrial", "infrastructure", "mixed"],
396
+ help="Asset type (default: commercial)",
397
+ )
398
+ args = parser.parse_args()
399
+
400
+ framework = detect_jurisdiction(args.input)
401
+
402
+ if framework:
403
+ result = build_output(framework, args.asset_type)
404
+ print(json.dumps(result, indent=2, ensure_ascii=False))
405
+ else:
406
+ error = {
407
+ "error": "jurisdiction_unknown",
408
+ "action": "ASK THE USER: Which country/city/state is this property located in?",
409
+ "reason": (
410
+ "Cannot cite tax statutes or legal requirements without confirmed jurisdiction. "
411
+ "Fiscal and legal obligations differ significantly between countries."
412
+ ),
413
+ "supported_jurisdictions": list(JURISDICTION_MAP.keys()),
414
+ }
415
+ print(json.dumps(error, indent=2, ensure_ascii=False))
416
+ sys.exit(1)
417
+
418
+
419
+ if __name__ == "__main__":
420
+ main()
scripts/validate_lease.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ validate_lease.py — Lease completeness and risk checker by jurisdiction.
4
+
5
+ Usage:
6
+ python scripts/validate_lease.py --lease-file contract.txt --jurisdiction uk --party tenant
7
+ python scripts/validate_lease.py --lease-file lease.txt --jurisdiction spain --asset-type commercial
8
+ python scripts/validate_lease.py --lease-file nnn.txt --jurisdiction usa --asset-type retail
9
+
10
+ Output:
11
+ JSON with per-item status (PRESENT / AMBIGUOUS / ABSENT), counts,
12
+ jurisdiction-specific flags, and overall GREEN/YELLOW/RED status.
13
+
14
+ Note: Detection is keyword-based — FIRST PASS only.
15
+ All ABSENT and AMBIGUOUS items must be verified manually by a qualified lawyer.
16
+ """
17
+
18
+ import argparse, json, sys, os
19
+
20
+ UNIVERSAL_ITEMS = [
21
+ {"id":"U01","name":"rent_and_payment_terms",
22
+ "keywords":["rent","renta","loyer","miete","payment","pago","mensualidad"],
23
+ "desc":"Rent amount, currency, payment frequency, late payment consequences",
24
+ "risk_if_absent":"CRITICAL — fundamental commercial term missing"},
25
+ {"id":"U02","name":"rent_escalation_review",
26
+ "keywords":["escalation","review","revision","actualizacion","indexation","CPI","IPC","RPI","increment"],
27
+ "desc":"Rent escalation mechanism: fixed %, CPI-linked, open market review, or stepped",
28
+ "risk_if_absent":"HIGH — no escalation = rent erodes in real terms over lease term"},
29
+ {"id":"U03","name":"security_deposit_or_guarantee",
30
+ "keywords":["deposit","deposito","guarantee","garantia","aval","bond","fianza","security"],
31
+ "desc":"Security deposit or bank guarantee: amount, form, draw conditions, return timeline",
32
+ "risk_if_absent":"HIGH — landlord has no security against default"},
33
+ {"id":"U04","name":"lease_term_and_commencement",
34
+ "keywords":["term","plazo","duration","commencement","expiry","vencimiento","inicio","lease period"],
35
+ "desc":"Lease start date, end date, total duration, conditions precedent to commencement",
36
+ "risk_if_absent":"CRITICAL — without defined term, lease cannot be properly valued or enforced"},
37
+ {"id":"U05","name":"permitted_use",
38
+ "keywords":["use","uso","permitted","permiso","purpose","actividad","destino","occupation"],
39
+ "desc":"Specific permitted use, exclusivity provisions, restrictions on use",
40
+ "risk_if_absent":"HIGH — tenant may use for incompatible purposes"},
41
+ {"id":"U06","name":"assignment_and_subletting",
42
+ "keywords":["assignment","cesion","subletting","subarriendo","transfer","consent","alienation"],
43
+ "desc":"Conditions for assignment and subletting: consent required, landlord response time",
44
+ "risk_if_absent":"MEDIUM — silence defaults to statutory position which varies by jurisdiction"},
45
+ {"id":"U07","name":"termination_and_default",
46
+ "keywords":["termination","resolucion","default","incumplimiento","breach","cure","remedy"],
47
+ "desc":"Termination rights, cure periods (monetary and non-monetary), consequences of default",
48
+ "risk_if_absent":"HIGH — no defined cure period creates uncertainty for both parties"},
49
+ {"id":"U08","name":"maintenance_and_repair",
50
+ "keywords":["maintenance","mantenimiento","repair","reparacion","upkeep","structural","fabric"],
51
+ "desc":"Allocation of maintenance obligations (structural vs non-structural, HVAC, common areas)",
52
+ "risk_if_absent":"MEDIUM — leads to disputes; defaults to statutory allocation"},
53
+ {"id":"U09","name":"insurance_requirements",
54
+ "keywords":["insurance","seguro","assurance","liability","responsabilidad","public liability","property insurance"],
55
+ "desc":"Required insurance types, minimum cover amounts, naming as additional insured",
56
+ "risk_if_absent":"MEDIUM — uninsured losses can exceed lease economics"},
57
+ {"id":"U10","name":"alterations_and_fit_out",
58
+ "keywords":["alteration","obras","fit-out","improvement","mejora","reinstatement","reposicion","reinstate"],
59
+ "desc":"Consent for alterations, ownership of improvements, reinstatement obligation at expiry",
60
+ "risk_if_absent":"MEDIUM — ownership disputes at expiry"},
61
+ {"id":"U11","name":"force_majeure",
62
+ "keywords":["force majeure","fuerza mayor","act of god","pandemic","pandemia","unavoidable","supervening"],
63
+ "desc":"Force majeure definition, rent abatement or termination right, maximum duration",
64
+ "risk_if_absent":"MEDIUM — post-COVID standard inclusion; absence creates uncertainty"},
65
+ {"id":"U12","name":"dispute_resolution_and_governing_law",
66
+ "keywords":["dispute","arbitration","arbitraje","litigio","court","tribunal","governing law","jurisdiction"],
67
+ "desc":"Governing law, jurisdiction, dispute resolution mechanism",
68
+ "risk_if_absent":"HIGH — parties default to potentially inconvenient or costly forum"},
69
+ {"id":"U13","name":"notices",
70
+ "keywords":["notice","notificacion","notification","address for service","direccion"],
71
+ "desc":"Notice method, service addresses, deemed receipt timing",
72
+ "risk_if_absent":"MEDIUM — invalid notices can defeat break clauses and renewal rights"},
73
+ {"id":"U14","name":"indemnity_and_liability_cap",
74
+ "keywords":["indemnity","indemnidad","liability","responsabilidad","cap","limitation","consequential"],
75
+ "desc":"Mutual indemnities, liability caps, exclusion of consequential losses",
76
+ "risk_if_absent":"HIGH — uncapped liability exposure"},
77
+ {"id":"U15","name":"rent_free_or_incentives",
78
+ "keywords":["rent free","rent-free","incentive","franquicia","holiday","contribution","fit out contribution"],
79
+ "desc":"Rent-free period, fit-out contribution, clawback if tenant exits early",
80
+ "risk_if_absent":"LOW — relevant if incentives are part of deal economics"},
81
+ ]
82
+
83
+ JURISDICTION_ITEMS = {
84
+ "uk": [
85
+ {"id":"UK01","name":"lta_1954_status",
86
+ "keywords":["1954","LTA","security of tenure","contracting out","statutory declaration","38A","inside the act","outside the act"],
87
+ "desc":"LTA 1954: is lease inside or outside the Act? If outside: s.38A notice + statutory declaration required BEFORE execution",
88
+ "risk_if_absent":"CRITICAL — if contracting-out procedure not followed, tenant has statutory renewal rights"},
89
+ {"id":"UK02","name":"break_clause_conditions",
90
+ "keywords":["break","option to break","break notice","break condition","vacant possession","break date"],
91
+ "desc":"Break clause: notice period (typically 6 months), pre-conditions (no arrears, vacant possession, covenant compliance)",
92
+ "risk_if_absent":"HIGH if break expected — poorly drafted conditions frequently prevent exercise"},
93
+ {"id":"UK03","name":"service_charge_rics",
94
+ "keywords":["service charge","RICS","management fee","sinking fund","service cost","audit service charge"],
95
+ "desc":"Service charge: RICS Professional Statement 2018 compliance, audit rights, annual cap",
96
+ "risk_if_absent":"MEDIUM — without cap/audit rights, service charge exposure is uncontrolled"},
97
+ {"id":"UK04","name":"dilapidations_and_schedule_of_condition",
98
+ "keywords":["dilapidation","schedule of condition","yield up","repair covenant","reinstate","decorating covenant"],
99
+ "desc":"Dilapidations provisions; schedule of condition if property not in prime condition",
100
+ "risk_if_absent":"HIGH for tenant — without schedule of condition, liable for full repair standard at expiry"},
101
+ {"id":"UK05","name":"snda",
102
+ "keywords":["SNDA","subordination","non-disturbance","attornment","lender consent","mortgagee"],
103
+ "desc":"SNDA if property is mortgaged — protects tenant's lease if lender forecloses",
104
+ "risk_if_absent":"HIGH if property mortgaged — foreclosure could extinguish tenant lease"},
105
+ {"id":"UK06","name":"rent_review_mechanism",
106
+ "keywords":["rent review","open market","upward only","OMR","market rent","review date"],
107
+ "desc":"Rent review type (open market / indexed / stepped), frequency, upward-only clause",
108
+ "risk_if_absent":"MEDIUM — no review mechanism means rent fixed for entire term"},
109
+ ],
110
+ "spain": [
111
+ {"id":"ES01","name":"ipc_indexation",
112
+ "keywords":["IPC","actualizacion","revision anual","INE","indice","IPC anual","actualizacion renta"],
113
+ "desc":"Rent update: IPC (INE) or agreed alternative (LAU Art.18) — must be express if not IPC",
114
+ "risk_if_absent":"MEDIUM — defaults to IPC; if different indexation intended, must be explicit"},
115
+ {"id":"ES02","name":"deposito_2_meses",
116
+ "keywords":["deposito","fianza","2 mensualidades","LAU 36","garantia adicional","aval bancario"],
117
+ "desc":"Mandatory 2-month deposit (LAU Art.36 for local); additional guarantee if agreed",
118
+ "risk_if_absent":"HIGH — 2-month deposit is legally mandatory; non-provision is non-compliance"},
119
+ {"id":"ES03","name":"break_clause",
120
+ "keywords":["clausula de salida","break","resolucion anticipada","penalizacion","preaviso salida"],
121
+ "desc":"Early termination clause: notice period, penalty, conditions",
122
+ "risk_if_absent":"LOW-MEDIUM — without break clause, contract binding for full term"},
123
+ {"id":"ES04","name":"iva_y_retencion_fiscal",
124
+ "keywords":["IVA","21%","impuesto valor","retencion","IRPF","19%","factura","sujeto a IVA"],
125
+ "desc":"IVA (21%) on rent; IRPF retention (19%) if tenant is a company or professional",
126
+ "risk_if_absent":"HIGH — unclear fiscal treatment creates tax compliance risk for both parties"},
127
+ {"id":"ES05","name":"prorroga_y_vencimiento",
128
+ "keywords":["prorroga","prorroga tacita","vencimiento","renovacion","notificacion vencimiento"],
129
+ "desc":"Renewal/extension provisions, tacit renewal conditions, notice requirements for non-renewal",
130
+ "risk_if_absent":"MEDIUM — LAU provisions apply by default; may not match parties' intentions"},
131
+ ],
132
+ "usa": [
133
+ {"id":"US01","name":"lease_type_classification",
134
+ "keywords":["NNN","triple net","gross","modified gross","full service","net lease","absolute net"],
135
+ "desc":"Lease type explicitly stated: FSG / Modified Gross / NNN / Absolute NNN — determines cost allocation",
136
+ "risk_if_absent":"CRITICAL — without explicit type, CAM and expense allocation is ambiguous"},
137
+ {"id":"US02","name":"cam_definition_and_cap",
138
+ "keywords":["CAM","common area","operating expense","expense stop","cap","gross-up","audit right"],
139
+ "desc":"CAM definition (inclusions/exclusions), annual cap (typically 5%), gross-up, audit rights",
140
+ "risk_if_absent":"HIGH for tenant — uncapped CAM creates unquantifiable occupancy cost"},
141
+ {"id":"US03","name":"snda_and_estoppel",
142
+ "keywords":["SNDA","estoppel","subordination","non-disturbance","attornment","lender"],
143
+ "desc":"SNDA and estoppel certificate requirements (required for CMBS and most institutional financing)",
144
+ "risk_if_absent":"HIGH — without SNDA, tenant lease may be extinguished on foreclosure"},
145
+ {"id":"US04","name":"cotenancy_clause",
146
+ "keywords":["co-tenancy","cotenancy","anchor","dark","go-dark","percentage rent"],
147
+ "desc":"Co-tenancy clause: rent reduction or termination right if anchor tenant vacates (retail)",
148
+ "risk_if_absent":"MEDIUM for retail — without co-tenancy, tenant bears full anchor risk"},
149
+ {"id":"US05","name":"holdover_provision",
150
+ "keywords":["holdover","hold over","month to month","150%","200%","holdover rent"],
151
+ "desc":"Holdover rent (typically 150% of last monthly rent) if tenant stays after expiry",
152
+ "risk_if_absent":"MEDIUM — defaults to month-to-month at existing rent"},
153
+ {"id":"US06","name":"renewal_option",
154
+ "keywords":["renewal","option to renew","extension option","FMR","fair market rent","notice of renewal"],
155
+ "desc":"Renewal option: number, notice deadline (typically 6-12 months before expiry), rent determination",
156
+ "risk_if_absent":"LOW — no statutory renewal rights in US; without option, no right to renew"},
157
+ ],
158
+ "india": [
159
+ {"id":"IN01","name":"lock_in_period",
160
+ "keywords":["lock-in","lock in","lockin","minimum term","early exit penalty","lock in period"],
161
+ "desc":"Lock-in period during which neither party can terminate (typically 3 years for commercial)",
162
+ "risk_if_absent":"HIGH for landlord — tenant can exit without penalty"},
163
+ {"id":"IN02","name":"gst_on_rent",
164
+ "keywords":["GST","18%","CGST","SGST","input tax credit","ITC","GST registration","GSTIN"],
165
+ "desc":"GST at 18% on commercial rent if landlord's aggregate turnover > INR 20L; ITC eligibility",
166
+ "risk_if_absent":"HIGH — GST non-compliance exposes landlord to demand, interest and penalty"},
167
+ {"id":"IN03","name":"tds_on_rent",
168
+ "keywords":["TDS","tax deduction","194-I","194IB","Form 16A","26QC","TDS certificate"],
169
+ "desc":"TDS obligations: Sec.194-I (10%) for companies; Sec.194-IB (5%) for individuals > INR 50K/month",
170
+ "risk_if_absent":"HIGH — non-deduction makes payer assessee-in-default"},
171
+ {"id":"IN04","name":"leave_and_license_vs_lease",
172
+ "keywords":["leave and license","leave & license","licence","license fee","licensor","licensee"],
173
+ "desc":"Clarify if agreement is lease or leave & license — different legal protections and eviction remedies",
174
+ "risk_if_absent":"HIGH — misclassification applies wrong legal regime"},
175
+ {"id":"IN05","name":"rera_compliance",
176
+ "keywords":["RERA","Real Estate Regulatory","RERA number","RERA registration","promoter"],
177
+ "desc":"If residential: RERA registration number and compliance with RERA obligations",
178
+ "risk_if_absent":"HIGH if residential — RERA non-compliance is a criminal offence"},
179
+ ],
180
+ "france": [
181
+ {"id":"FR01","name":"bail_commercial_9_ans",
182
+ "keywords":["9 ans","bail commercial","3-6-9","résiliation triennale","renouvellement","décret 1953"],
183
+ "desc":"Bail commercial: 9-year minimum; tenant triennal exit confirmed; statutory renewal right",
184
+ "risk_if_absent":"CRITICAL — non-compliance with bail commercial rules invalidates the lease structure"},
185
+ {"id":"FR02","name":"indexation_ilc_ilat",
186
+ "keywords":["ILC","ILAT","INSEE","révision","loyer indexé","indice"],
187
+ "desc":"Rent indexation: ILC (shops) or ILAT (offices/logistics) — published quarterly by INSEE",
188
+ "risk_if_absent":"MEDIUM — defaults to ILC; if different index intended, must be expressed"},
189
+ {"id":"FR03","name":"charges_loi_pinel",
190
+ "keywords":["charges","travaux","article 606","gros travaux","repartition charges","loi pinel"],
191
+ "desc":"Charges allocation per Loi Pinel 2014 reform: list of charges recoverable from tenant vs landlord Art.606",
192
+ "risk_if_absent":"HIGH — Loi Pinel requires explicit allocation; silence creates disputes"},
193
+ ],
194
+ "germany": [
195
+ {"id":"DE01","name":"schriftform_written_form",
196
+ "keywords":["Schriftform","written form","signature","unterschrift","§550","BGB 550"],
197
+ "desc":"Written form (BGB §550): leases >1 year must be fully in writing to run for full term",
198
+ "risk_if_absent":"CRITICAL — incomplete written form = lease treated as indefinite-term, terminable with notice"},
199
+ {"id":"DE02","name":"nebenkosten_allocation",
200
+ "keywords":["Nebenkosten","Betriebskosten","operating costs","Nebenkostenabrechnung","Heizkostenabrechnung"],
201
+ "desc":"Nebenkosten (operating costs) allocation, annual reconciliation obligation",
202
+ "risk_if_absent":"HIGH — without clear allocation, landlord cannot recover all operating costs"},
203
+ {"id":"DE03","name":"mietzins_anpassung",
204
+ "keywords":["Mietanpassung","Indexmiete","CPI","Verbraucherpreisindex","Staffelmiete","Wertsicherungsklausel"],
205
+ "desc":"Rent adjustment: index-linked (Indexmiete) or stepped (Staffelmiete) — both require express agreement",
206
+ "risk_if_absent":"MEDIUM — no adjustment: rent fixed for entire term"},
207
+ ],
208
+ }
209
+
210
+
211
+ def check_item(text, item):
212
+ text_lower = text.lower()
213
+ hits = sum(1 for k in item["keywords"] if k.lower() in text_lower)
214
+ total = len(item["keywords"])
215
+ if hits == 0:
216
+ return "ABSENT"
217
+ elif hits >= max(1, int(total * 0.4)):
218
+ return "PRESENT"
219
+ else:
220
+ return "AMBIGUOUS"
221
+
222
+
223
+ def evaluate_lease(text, jurisdiction, party, asset_type):
224
+ all_items = UNIVERSAL_ITEMS + JURISDICTION_ITEMS.get(jurisdiction, [])
225
+ results, absent_ids, ambiguous_ids = [], [], []
226
+ for item in all_items:
227
+ status = check_item(text, item)
228
+ results.append({"id":item["id"],"name":item["name"],"status":status,
229
+ "desc":item["desc"],"risk_if_absent":item.get("risk_if_absent","")})
230
+ if status == "ABSENT": absent_ids.append(item["id"])
231
+ elif status == "AMBIGUOUS": ambiguous_ids.append(item["id"])
232
+ n_absent, n_ambiguous = len(absent_ids), len(ambiguous_ids)
233
+ if n_absent == 0 and n_ambiguous <= 2:
234
+ overall = "GREEN"; msg = "Lease appears substantially complete. Verify AMBIGUOUS items manually."
235
+ elif n_absent <= 2 and (n_absent + n_ambiguous) <= 5:
236
+ overall = "YELLOW"; msg = f"{n_absent} ABSENT and {n_ambiguous} AMBIGUOUS items. Legal review required."
237
+ else:
238
+ overall = "RED"; msg = f"{n_absent} ABSENT items — material gaps. Do not execute without legal review."
239
+ return {
240
+ "jurisdiction": jurisdiction, "party_perspective": party, "asset_type": asset_type,
241
+ "summary": {"total_items_checked": len(all_items), "present": len(all_items)-n_absent-n_ambiguous,
242
+ "ambiguous": n_ambiguous, "absent": n_absent,
243
+ "overall_status": overall, "message": msg},
244
+ "absent_item_ids": absent_ids, "ambiguous_item_ids": ambiguous_ids, "detail": results,
245
+ "note": ("Keyword-based FIRST PASS only. PRESENT = keywords found, not that clause is legally adequate. "
246
+ "All items must be reviewed by a qualified lawyer in the applicable jurisdiction."),
247
+ }
248
+
249
+
250
+ def main():
251
+ parser = argparse.ArgumentParser(description="Lease completeness checker by jurisdiction.")
252
+ parser.add_argument("--lease-file", required=True)
253
+ parser.add_argument("--jurisdiction", default="generic",
254
+ choices=["uk","spain","usa","india","germany","france","generic"])
255
+ parser.add_argument("--party", default="landlord", choices=["landlord","tenant"])
256
+ parser.add_argument("--asset-type", default="commercial",
257
+ choices=["commercial","retail","industrial","residential","office"])
258
+ args = parser.parse_args()
259
+ if not os.path.exists(args.lease_file):
260
+ print(json.dumps({"error": f"File not found: {args.lease_file}"})); sys.exit(1)
261
+ with open(args.lease_file, encoding="utf-8", errors="replace") as f:
262
+ text = f.read()
263
+ if len(text.strip()) < 50:
264
+ print(json.dumps({"error": "File appears empty or too short"})); sys.exit(1)
265
+ print(json.dumps(evaluate_lease(text, args.jurisdiction, args.party, args.asset_type),
266
+ indent=2, ensure_ascii=False))
267
+
268
+ if __name__ == "__main__":
269
+ main()
scripts/validate_ltv.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ validate_ltv.py — Calculates LTV and validates against jurisdiction-specific thresholds.
4
+
5
+ Usage:
6
+ python scripts/validate_ltv.py --loan 8500000 --value 12000000 --country uk --type commercial
7
+ python scripts/validate_ltv.py --loan 5000000 --value 8000000 --country spain --type residential
8
+
9
+ Output:
10
+ JSON with LTV %, maximum permitted LTV, safety margin, and GREEN/YELLOW/RED status.
11
+
12
+ Note: Thresholds reflect typical institutional lender requirements, not regulatory caps
13
+ (unless noted). Actual lender requirements vary — verify with specific lender/deal terms.
14
+ """
15
+
16
+ import argparse
17
+ import json
18
+ import sys
19
+
20
+ # ─── LTV Thresholds by Country and Asset Type ─────────────────────────────────
21
+ # max_normal: Maximum LTV for GREEN status
22
+ # max_stress: Maximum LTV for YELLOW status (above this = RED)
23
+ # warning_buffer: how close to max_normal triggers a YELLOW-within-GREEN warning
24
+
25
+ LTV_THRESHOLDS = {
26
+ "spain": {
27
+ "residential": {
28
+ "max_normal": 0.80, "max_stress": 0.85,
29
+ "note": "Spain residential: typical bank max 80% (first-home exceptions to 90%)",
30
+ "regulatory_note": "Banco de España macroprudential guidance",
31
+ },
32
+ "commercial": {
33
+ "max_normal": 0.65, "max_stress": 0.70,
34
+ "note": "Spain CRE: conservative banca española standard",
35
+ "regulatory_note": "Typical Spanish CRE lending practice",
36
+ },
37
+ "industrial": {
38
+ "max_normal": 0.65, "max_stress": 0.70,
39
+ "note": "Spain industrial / logistics",
40
+ "regulatory_note": "Typical Spanish industrial lending",
41
+ },
42
+ "infrastructure": {
43
+ "max_normal": 0.75, "max_stress": 0.80,
44
+ "note": "Spain infrastructure / PPP project finance",
45
+ "regulatory_note": "Typical project finance senior debt",
46
+ },
47
+ "mixed": {
48
+ "max_normal": 0.65, "max_stress": 0.70,
49
+ "note": "Spain mixed-use: apply most conservative component",
50
+ "regulatory_note": "Use lower of component thresholds",
51
+ },
52
+ },
53
+
54
+ "uk": {
55
+ "residential": {
56
+ "max_normal": 0.85, "max_stress": 0.90,
57
+ "note": "UK residential mortgage (standard); BTL typically max 75-80%",
58
+ "regulatory_note": "PRA / FCA mortgage regulation",
59
+ },
60
+ "commercial": {
61
+ "max_normal": 0.70, "max_stress": 0.75,
62
+ "note": "UK CRE: clearing bank / debt fund standard",
63
+ "regulatory_note": "Typical UK commercial real estate lending",
64
+ },
65
+ "industrial": {
66
+ "max_normal": 0.70, "max_stress": 0.75,
67
+ "note": "UK industrial / logistics",
68
+ "regulatory_note": "Typical UK industrial lending",
69
+ },
70
+ "infrastructure": {
71
+ "max_normal": 0.80, "max_stress": 0.85,
72
+ "note": "UK PFI / infrastructure project finance",
73
+ "regulatory_note": "Typical UK infrastructure project finance",
74
+ },
75
+ "mixed": {
76
+ "max_normal": 0.70, "max_stress": 0.75,
77
+ "note": "UK mixed-use",
78
+ "regulatory_note": "Apply lower of component thresholds",
79
+ },
80
+ },
81
+
82
+ "usa": {
83
+ "residential": {
84
+ "max_normal": 0.80, "max_stress": 0.85,
85
+ "note": "US residential conventional mortgage; FHA up to 96.5%",
86
+ "regulatory_note": "Fannie Mae / Freddie Mac conventional guidelines",
87
+ },
88
+ "commercial": {
89
+ "max_normal": 0.75, "max_stress": 0.80,
90
+ "note": "US CRE: CMBS / life company standard",
91
+ "regulatory_note": "Typical CMBS underwriting guideline",
92
+ },
93
+ "industrial": {
94
+ "max_normal": 0.70, "max_stress": 0.75,
95
+ "note": "US industrial / warehouse",
96
+ "regulatory_note": "Typical US industrial lending",
97
+ },
98
+ "infrastructure": {
99
+ "max_normal": 0.75, "max_stress": 0.80,
100
+ "note": "US project finance / infrastructure",
101
+ "regulatory_note": "Typical US infrastructure project finance",
102
+ },
103
+ "mixed": {
104
+ "max_normal": 0.70, "max_stress": 0.75,
105
+ "note": "US mixed-use",
106
+ "regulatory_note": "Apply lower of component thresholds",
107
+ },
108
+ },
109
+
110
+ "germany": {
111
+ "residential": {
112
+ "max_normal": 0.80, "max_stress": 0.85,
113
+ "note": "Germany residential (Wohnimmobilien): Pfandbrief-eligible up to 60%; total to 80%",
114
+ "regulatory_note": "Pfandbriefgesetz (PfandBG) mortgage lending value requirements",
115
+ },
116
+ "commercial": {
117
+ "max_normal": 0.60, "max_stress": 0.65,
118
+ "note": "Germany CRE: conservative Pfandbrief bank standard",
119
+ "regulatory_note": "BaFin / Pfandbrief mortgage lending value",
120
+ },
121
+ "industrial": {
122
+ "max_normal": 0.65, "max_stress": 0.70,
123
+ "note": "Germany industrial / logistics",
124
+ "regulatory_note": "Typical German industrial lending",
125
+ },
126
+ "infrastructure": {
127
+ "max_normal": 0.70, "max_stress": 0.75,
128
+ "note": "Germany infrastructure project finance",
129
+ "regulatory_note": "Typical German project finance",
130
+ },
131
+ "mixed": {
132
+ "max_normal": 0.60, "max_stress": 0.65,
133
+ "note": "Germany mixed-use: apply conservative commercial threshold",
134
+ "regulatory_note": "Apply lower of component thresholds",
135
+ },
136
+ },
137
+
138
+ "france": {
139
+ "residential": {
140
+ "max_normal": 0.80, "max_stress": 0.85,
141
+ "note": "France residential mortgage",
142
+ "regulatory_note": "HCSF (Haut Conseil de Stabilité Financière) guidelines",
143
+ },
144
+ "commercial": {
145
+ "max_normal": 0.65, "max_stress": 0.70,
146
+ "note": "France CRE",
147
+ "regulatory_note": "Typical French CRE lending",
148
+ },
149
+ "industrial": {
150
+ "max_normal": 0.65, "max_stress": 0.70,
151
+ "note": "France logistique / industrial",
152
+ "regulatory_note": "Typical French industrial lending",
153
+ },
154
+ "infrastructure": {
155
+ "max_normal": 0.75, "max_stress": 0.80,
156
+ "note": "France PPP / infrastructure",
157
+ "regulatory_note": "Typical French infrastructure project finance",
158
+ },
159
+ "mixed": {
160
+ "max_normal": 0.65, "max_stress": 0.70,
161
+ "note": "France mixed-use",
162
+ "regulatory_note": "Apply lower of component thresholds",
163
+ },
164
+ },
165
+
166
+ "india": {
167
+ "residential": {
168
+ "max_normal": 0.75, "max_stress": 0.80,
169
+ "note": "India housing finance: RBI guideline max 75-90% by loan size",
170
+ "regulatory_note": "RBI Master Direction on Housing Finance",
171
+ },
172
+ "commercial": {
173
+ "max_normal": 0.65, "max_stress": 0.70,
174
+ "note": "India CRE: RBI CRE category lending norms",
175
+ "regulatory_note": "RBI CRE category guidelines (higher risk weight)",
176
+ },
177
+ "industrial": {
178
+ "max_normal": 0.65, "max_stress": 0.70,
179
+ "note": "India industrial",
180
+ "regulatory_note": "Typical Indian industrial lending",
181
+ },
182
+ "infrastructure": {
183
+ "max_normal": 0.70, "max_stress": 0.75,
184
+ "note": "India project finance / infrastructure",
185
+ "regulatory_note": "RBI infrastructure project finance guidelines",
186
+ },
187
+ "mixed": {
188
+ "max_normal": 0.65, "max_stress": 0.70,
189
+ "note": "India mixed-use",
190
+ "regulatory_note": "Apply lower of component thresholds",
191
+ },
192
+ },
193
+
194
+ "uae": {
195
+ "residential": {
196
+ "max_normal": 0.75, "max_stress": 0.80,
197
+ "note": "UAE residential mortgage: UAE Central Bank max 75% (nationals 80%)",
198
+ "regulatory_note": "UAE Central Bank Mortgage Regulation 2013",
199
+ },
200
+ "commercial": {
201
+ "max_normal": 0.65, "max_stress": 0.70,
202
+ "note": "UAE CRE",
203
+ "regulatory_note": "Typical UAE commercial real estate lending",
204
+ },
205
+ "industrial": {
206
+ "max_normal": 0.65, "max_stress": 0.70,
207
+ "note": "UAE industrial",
208
+ "regulatory_note": "Typical UAE industrial lending",
209
+ },
210
+ "infrastructure": {
211
+ "max_normal": 0.70, "max_stress": 0.75,
212
+ "note": "UAE project finance",
213
+ "regulatory_note": "Typical UAE/GCC project finance",
214
+ },
215
+ "mixed": {
216
+ "max_normal": 0.65, "max_stress": 0.70,
217
+ "note": "UAE mixed-use",
218
+ "regulatory_note": "Apply lower of component thresholds",
219
+ },
220
+ },
221
+
222
+ "default": {
223
+ "residential": {
224
+ "max_normal": 0.80, "max_stress": 0.85,
225
+ "note": "Industry default — jurisdiction not specified",
226
+ "regulatory_note": "General market reference",
227
+ },
228
+ "commercial": {
229
+ "max_normal": 0.70, "max_stress": 0.75,
230
+ "note": "Industry default — jurisdiction not specified",
231
+ "regulatory_note": "General market reference",
232
+ },
233
+ "industrial": {
234
+ "max_normal": 0.70, "max_stress": 0.75,
235
+ "note": "Industry default — jurisdiction not specified",
236
+ "regulatory_note": "General market reference",
237
+ },
238
+ "infrastructure": {
239
+ "max_normal": 0.75, "max_stress": 0.80,
240
+ "note": "Industry default — jurisdiction not specified",
241
+ "regulatory_note": "General market reference",
242
+ },
243
+ "mixed": {
244
+ "max_normal": 0.70, "max_stress": 0.75,
245
+ "note": "Industry default — jurisdiction not specified",
246
+ "regulatory_note": "General market reference",
247
+ },
248
+ },
249
+ }
250
+
251
+
252
+ # ─── Core Calculation ──────────────────────────────────────────────────────────
253
+
254
+ def evaluate_ltv(
255
+ loan: float,
256
+ value: float,
257
+ country: str = "default",
258
+ asset_type: str = "commercial",
259
+ ) -> dict:
260
+ if value <= 0:
261
+ return {"error": "Property value must be greater than 0"}
262
+ if loan < 0:
263
+ return {"error": "Loan amount cannot be negative"}
264
+
265
+ ltv = loan / value
266
+ country_thresholds = LTV_THRESHOLDS.get(country, LTV_THRESHOLDS["default"])
267
+ thr = country_thresholds.get(asset_type, country_thresholds.get("commercial", LTV_THRESHOLDS["default"]["commercial"]))
268
+
269
+ headroom = thr["max_normal"] - ltv
270
+ headroom_stress = thr["max_stress"] - ltv
271
+
272
+ # Status
273
+ if ltv <= thr["max_normal"]:
274
+ if headroom >= 0.05:
275
+ status = "GREEN"
276
+ status_detail = (
277
+ f"LTV {ltv*100:.1f}% is within the {thr['max_normal']*100:.0f}% normal threshold "
278
+ f"with {headroom*100:.1f}% headroom. Adequate collateral coverage."
279
+ )
280
+ else:
281
+ status = "YELLOW"
282
+ status_detail = (
283
+ f"LTV {ltv*100:.1f}% is within the {thr['max_normal']*100:.0f}% normal threshold "
284
+ f"but headroom is only {headroom*100:.1f}% — below the 5% comfort buffer. "
285
+ f"Monitor closely; any value decline pushes into breach territory."
286
+ )
287
+ elif ltv <= thr["max_stress"]:
288
+ status = "YELLOW"
289
+ status_detail = (
290
+ f"LTV {ltv*100:.1f}% exceeds normal maximum ({thr['max_normal']*100:.0f}%) "
291
+ f"but is within stress maximum ({thr['max_stress']*100:.0f}%). "
292
+ f"Review underwriting assumptions; consider additional equity or collateral."
293
+ )
294
+ else:
295
+ status = "RED"
296
+ status_detail = (
297
+ f"LTV {ltv*100:.1f}% EXCEEDS stress maximum of {thr['max_stress']*100:.0f}%. "
298
+ f"ESCALATE — this loan structure is outside standard market parameters. "
299
+ f"Additional equity injection required: "
300
+ f"{(loan - value * thr['max_stress']):,.0f} units of currency."
301
+ )
302
+
303
+ # Required loan reduction for GREEN
304
+ max_loan_normal = value * thr["max_normal"]
305
+ max_loan_stress = value * thr["max_stress"]
306
+ required_reduction = max(0, loan - max_loan_normal)
307
+
308
+ return {
309
+ "inputs": {
310
+ "loan": loan,
311
+ "property_value": value,
312
+ "country": country,
313
+ "asset_type": asset_type,
314
+ },
315
+ "result": {
316
+ "ltv": round(ltv, 4),
317
+ "ltv_pct": f"{ltv * 100:.2f}%",
318
+ "equity_pct": f"{(1 - ltv) * 100:.2f}%",
319
+ "equity_amount": round(value - loan, 0),
320
+ },
321
+ "threshold_applied": {
322
+ "max_normal_pct": f"{thr['max_normal'] * 100:.0f}%",
323
+ "max_stress_pct": f"{thr['max_stress'] * 100:.0f}%",
324
+ "max_loan_at_normal": round(max_loan_normal, 0),
325
+ "max_loan_at_stress": round(max_loan_stress, 0),
326
+ "note": thr["note"],
327
+ "regulatory_note": thr["regulatory_note"],
328
+ },
329
+ "headroom": {
330
+ "vs_normal_threshold_pct": f"{headroom * 100:+.2f}%",
331
+ "vs_stress_threshold_pct": f"{headroom_stress * 100:+.2f}%",
332
+ "loan_reduction_needed_for_green": round(required_reduction, 0),
333
+ },
334
+ "status": status,
335
+ "status_detail": status_detail,
336
+ "escalation_required": status == "RED",
337
+ }
338
+
339
+
340
+ # ─── CLI ──────────────────────────────────────────────────────────────────────
341
+
342
+ def main():
343
+ parser = argparse.ArgumentParser(
344
+ description="Calculate LTV with jurisdiction-specific thresholds."
345
+ )
346
+ parser.add_argument("--loan", type=float, required=True, help="Loan amount")
347
+ parser.add_argument("--value", type=float, required=True, help="Property market value")
348
+ parser.add_argument(
349
+ "--country",
350
+ default="default",
351
+ choices=["spain", "uk", "usa", "germany", "france", "india", "uae", "singapore", "default"],
352
+ help="Country (default: default)",
353
+ )
354
+ parser.add_argument(
355
+ "--type",
356
+ dest="asset_type",
357
+ default="commercial",
358
+ choices=["residential", "commercial", "industrial", "infrastructure", "mixed"],
359
+ help="Asset type (default: commercial)",
360
+ )
361
+ args = parser.parse_args()
362
+
363
+ result = evaluate_ltv(args.loan, args.value, args.country, args.asset_type)
364
+ print(json.dumps(result, indent=2, ensure_ascii=False))
365
+
366
+
367
+ if __name__ == "__main__":
368
+ main()
scripts/validate_stamp_duty.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ validate_stamp_duty.py — Multi-jurisdiction property transfer tax estimator.
4
+
5
+ Usage:
6
+ python scripts/validate_stamp_duty.py --country spain --value 2500000
7
+ python scripts/validate_stamp_duty.py --country uk --value 1500000 --asset-type residential --additional-dwelling
8
+ python scripts/validate_stamp_duty.py --country usa --value 3000000 --region new_york
9
+ python scripts/validate_stamp_duty.py --country india --value 15000000 --region maharashtra
10
+ python scripts/validate_stamp_duty.py --country spain --value 500000 --is-new --region madrid
11
+ python scripts/validate_stamp_duty.py --country germany --value 2000000 --region berlin
12
+
13
+ IMPORTANT:
14
+ Tax rates change frequently. This script provides ESTIMATES for analysis purposes only.
15
+ Always verify current rates with qualified local tax counsel before any transaction.
16
+ This output does not constitute tax advice.
17
+ """
18
+
19
+ import argparse
20
+ import json
21
+ import sys
22
+
23
+ # ─── SPAIN ────────────────────────────────────────────────────────────────────
24
+
25
+ SPAIN_ITP_BY_CCAA = {
26
+ "andalucia": {"general": 0.07, "note": "Reduced 3.5% for buyers under 35 with conditions"},
27
+ "aragon": {"general": 0.08, "note": ""},
28
+ "asturias": {"general": 0.08, "note": ""},
29
+ "baleares": {"general": 0.11, "note": "Up to 12% for properties > EUR 2M"},
30
+ "canarias": {"general": 0.065, "note": "IGIC (not IVA) applies in Canarias for new builds"},
31
+ "cantabria": {"general": 0.10, "note": ""},
32
+ "castilla_la_mancha": {"general": 0.09, "note": ""},
33
+ "castilla_leon": {"general": 0.08, "note": ""},
34
+ "cataluna": {"general": 0.10, "note": "Reduced 5% for buyers under 33 with conditions"},
35
+ "extremadura": {"general": 0.08, "note": "Reduced 7% for buyers under 35"},
36
+ "galicia": {"general": 0.10, "note": ""},
37
+ "la_rioja": {"general": 0.07, "note": ""},
38
+ "madrid": {"general": 0.06, "note": "Lowest ITP in mainland Spain"},
39
+ "murcia": {"general": 0.08, "note": ""},
40
+ "navarra": {"general": 0.06, "note": "Regimen foral — own tax legislation"},
41
+ "pais_vasco": {"general": 0.04, "note": "Regimen foral — Diputaciones Forales"},
42
+ "valencia": {"general": 0.10, "note": ""},
43
+ "default": {"general": 0.07, "note": "National reference — verify CCAA"},
44
+ }
45
+
46
+ SPAIN_AJD_BY_CCAA = {
47
+ "madrid": 0.0075, "cataluna": 0.015, "andalucia": 0.012,
48
+ "valencia": 0.02, "baleares": 0.012, "galicia": 0.015,
49
+ "pais_vasco": 0.005, "navarra": 0.005, "default": 0.015,
50
+ }
51
+
52
+
53
+ def calc_spain(price, buyer_type, asset_type, is_new, region):
54
+ rk = region.lower().replace(" ", "_").replace("-", "_")
55
+ itp_data = SPAIN_ITP_BY_CCAA.get(rk, SPAIN_ITP_BY_CCAA["default"])
56
+ itp_rate = itp_data["general"]
57
+ ajd_rate = SPAIN_AJD_BY_CCAA.get(rk, SPAIN_AJD_BY_CCAA["default"])
58
+ nr_retention = price * 0.03 if buyer_type == "non_resident" else 0
59
+
60
+ if is_new:
61
+ iva_rate = 0.10 if asset_type == "residential" else 0.21
62
+ iva = price * iva_rate
63
+ ajd = price * ajd_rate
64
+ total = iva + ajd
65
+ return {
66
+ "country": "Spain", "transaction_type": "New build (primera transmision)",
67
+ "region_ccaa": region, "price_eur": price,
68
+ "taxes": {
69
+ "IVA": {"amount": round(iva), "rate": f"{iva_rate*100:.0f}%",
70
+ "note": "10% residential / 21% commercial new build"},
71
+ "AJD": {"amount": round(ajd), "rate": f"{ajd_rate*100:.2f}%"},
72
+ "ITP": {"amount": 0, "note": "IVA and ITP are mutually exclusive — ITP does NOT apply to new builds"},
73
+ },
74
+ "total_buyer": round(total), "total_buyer_pct": f"{total/price*100:.2f}%",
75
+ "non_resident_retention_3pct": round(nr_retention),
76
+ "non_resident_note": (
77
+ "MANDATORY if seller is non-resident: buyer withholds 3% of price -> "
78
+ "Modelo 211 within 30 days of deed (IRNR Art.25.2). Buyer jointly liable."
79
+ if buyer_type == "non_resident" else "Seller is resident — no retention required"
80
+ ),
81
+ "seller_obligations": [
82
+ "Plusvalia municipal (IIVTNU): calculate by both real and objective method (STC TC 26/2021). Pay to municipality within 30 days.",
83
+ "IRPF/IRNR: declare capital gain in annual return or Modelo 210 (NR).",
84
+ ],
85
+ "additional_costs": ["Notary fees: ~EUR 600-2,500", "Land Registry: ~EUR 400-2,000"],
86
+ "disclaimer": "ESTIMATE ONLY. Verify with gestor/abogado before transaction.",
87
+ }
88
+ else:
89
+ itp = price * itp_rate
90
+ ajd = price * ajd_rate
91
+ total = itp + ajd
92
+ return {
93
+ "country": "Spain", "transaction_type": "Resale (segunda o posterior transmision)",
94
+ "region_ccaa": region, "price_eur": price,
95
+ "taxes": {
96
+ "ITP": {"amount": round(itp), "rate": f"{itp_rate*100:.0f}%",
97
+ "note": itp_data["note"] or f"Standard ITP for {region}"},
98
+ "AJD": {"amount": round(ajd), "rate": f"{ajd_rate*100:.2f}%"},
99
+ "IVA": {"amount": 0, "note": "IVA does NOT apply to resales"},
100
+ },
101
+ "total_buyer": round(total), "total_buyer_pct": f"{total/price*100:.2f}%",
102
+ "non_resident_retention_3pct": round(nr_retention),
103
+ "non_resident_note": (
104
+ "MANDATORY: buyer withholds 3% of price -> Modelo 211 within 30 days. "
105
+ "Buyer jointly liable if not withheld (IRNR Art.25.2 LIRNR)."
106
+ if buyer_type == "non_resident" else "Seller is resident — no retention required"
107
+ ),
108
+ "seller_obligations": [
109
+ "Plusvalia municipal (IIVTNU): calculate by BOTH methods (STC TC 26/2021). Use most favourable.",
110
+ "IRPF capital gains: declare in annual return. Exemptions: over-65s, reinvestment in main residence.",
111
+ ],
112
+ "additional_costs": ["Notary fees: ~EUR 600-2,500", "Land Registry: ~EUR 400-2,000"],
113
+ "disclaimer": "ESTIMATE ONLY. ITP rates change annually by CCAA. Verify with gestor/abogado.",
114
+ }
115
+
116
+
117
+ # ─── UK ───────────────────────────────────────────────────────────────────────
118
+
119
+ def calc_uk(price, buyer_type, asset_type, additional_dwelling):
120
+ if asset_type == "residential":
121
+ slabs = [(250_000, 0.00), (925_000, 0.05), (1_500_000, 0.10), (float("inf"), 0.12)]
122
+ else:
123
+ slabs = [(150_000, 0.00), (250_000, 0.02), (float("inf"), 0.05)]
124
+
125
+ sdlt_base = 0.0
126
+ prev = 0.0
127
+ breakdown = []
128
+ for limit, rate in slabs:
129
+ band = max(0.0, min(price, limit) - prev)
130
+ tax = band * rate
131
+ sdlt_base += tax
132
+ breakdown.append({"band_up_to": f"{limit:,.0f}" if limit < 1e18 else f"above {prev:,.0f}",
133
+ "rate": f"{rate*100:.0f}%", "band_amount": round(band), "tax": round(tax)})
134
+ prev = limit
135
+ if price <= limit:
136
+ break
137
+
138
+ add_s = price * 0.03 if additional_dwelling else 0.0
139
+ nr_s = price * 0.02 if buyer_type == "non_resident" else 0.0
140
+ total = sdlt_base + add_s + nr_s
141
+
142
+ return {
143
+ "country": "United Kingdom (England & Northern Ireland)",
144
+ "note": "Scotland uses LBTT; Wales uses LTT — different rates apply.",
145
+ "asset_type": asset_type, "buyer_type": buyer_type, "price_gbp": price,
146
+ "taxes": {
147
+ "SDLT_base": round(sdlt_base),
148
+ "slab_breakdown": breakdown,
149
+ "additional_dwelling_surcharge_3pct": round(add_s),
150
+ "non_resident_surcharge_2pct": round(nr_s),
151
+ },
152
+ "total_SDLT": round(total),
153
+ "effective_rate": f"{total/price*100:.2f}%",
154
+ "critical_deadline": "File SDLT1 return AND pay within 14 days of completion (SDLT Act 2003 s.76). Automatic GBP 100 penalty from day 1.",
155
+ "cgt_note": "Seller: CGT on residential property must be reported and paid within 60 days of completion via HMRC UK Property account.",
156
+ "disclaimer": "ESTIMATE ONLY. SDLT rules change. Verify with UK solicitor / HMRC before transaction.",
157
+ }
158
+
159
+
160
+ # ─── USA ──────────────────────────────────────────────────────────────────────
161
+
162
+ USA_STATE_RATES = {
163
+ "california": {"rate": 0.0011, "note": "County rate ~$1.10/$1,000; cities may add separately"},
164
+ "colorado": {"rate": 0.001, "note": "Documentary fee"},
165
+ "connecticut": {"rate": 0.0075, "note": "Conveyance tax"},
166
+ "delaware": {"rate": 0.03, "note": "3% split buyer/seller; first-time buyer relief available"},
167
+ "florida": {"rate": 0.007, "note": "Documentary stamps on deed"},
168
+ "georgia": {"rate": 0.001, "note": "Real estate transfer tax"},
169
+ "hawaii": {"rate": 0.015, "note": "Conveyance tax; progressive by price"},
170
+ "illinois": {"rate": 0.001, "note": "State rate; Cook County and Chicago add more"},
171
+ "maryland": {"rate": 0.005, "note": "State rate; county adds separately"},
172
+ "massachusetts": {"rate": 0.00456,"note": "$4.56 per $1,000 of price"},
173
+ "michigan": {"rate": 0.0075, "note": "State + county combined ~0.86%"},
174
+ "new_jersey": {"rate": 0.01, "note": "Realty Transfer Fee; mansion tax 1% over USD 1M"},
175
+ "new_york": {"rate": 0.004, "note": "State only; NYC adds 1-2.075%; mansion tax if >= USD 1M"},
176
+ "pennsylvania": {"rate": 0.01, "note": "State 1%; local adds (Philadelphia total ~3.278%)"},
177
+ "texas": {"rate": 0.0, "note": "No state real estate transfer tax"},
178
+ "virginia": {"rate": 0.0025, "note": "Grantor tax; buyer pays recordation separately"},
179
+ "washington": {"rate": 0.013, "note": "REET; progressive 1.1-3% by price"},
180
+ "generic": {"rate": 0.01, "note": "Generic estimate — verify specific state and county"},
181
+ }
182
+
183
+
184
+ def calc_usa(price, state):
185
+ sk = state.lower().replace(" ", "_")
186
+ sd = USA_STATE_RATES.get(sk, USA_STATE_RATES["generic"])
187
+ tax = price * sd["rate"]
188
+ mansion = 0.0
189
+ mansion_note = "N/A"
190
+ if sk == "new_york" and price >= 1_000_000:
191
+ brackets = [(2e6,0.01),(3e6,0.0125),(5e6,0.014),(10e6,0.015),(15e6,0.02),(20e6,0.025),(25e6,0.029),(1e18,0.039)]
192
+ for lim, rate in brackets:
193
+ if price < lim:
194
+ mansion = price * rate; break
195
+ mansion_note = f"NYC Mansion Tax at applicable rate on USD {price:,.0f}"
196
+ return {
197
+ "country": "USA", "state": state, "price_usd": price,
198
+ "taxes": {
199
+ "state_transfer_tax": {"amount": round(tax), "rate": f"{sd['rate']*100:.3f}%", "note": sd["note"]},
200
+ "mansion_tax": round(mansion) if mansion > 0 else "N/A",
201
+ "mansion_tax_note": mansion_note,
202
+ },
203
+ "total_transfer_taxes": round(tax + mansion),
204
+ "firpta_if_foreign_seller": (
205
+ "Buyer withholds 15% of AMOUNT REALIZED from foreign seller. "
206
+ "Exception: price <= USD 300K + buyer residence use = 0%. "
207
+ "300K-1M + buyer residence use = 10%. File Form 8288 within 20 days."
208
+ ),
209
+ "exchange_1031_note": "QI must be engaged BEFORE closing. 45-day ID + 180-day closing windows are absolute.",
210
+ "disclaimer": "ESTIMATE ONLY. Rates vary by state, county, city. Verify with local real estate attorney.",
211
+ }
212
+
213
+
214
+ # ─── INDIA ────────────────────────────────────────────────────────────────────
215
+
216
+ INDIA_RATES = {
217
+ "maharashtra": {"rate": 0.07, "reg": 0.01, "note": "+1% metro cess in Mumbai; women get 1% rebate"},
218
+ "delhi": {"rate": 0.06, "reg": 0.01, "note": "Women buyers: 4%"},
219
+ "karnataka": {"rate": 0.056, "reg": 0.01, "note": ""},
220
+ "tamil_nadu": {"rate": 0.07, "reg": 0.01, "note": ""},
221
+ "telangana": {"rate": 0.075, "reg": 0.005,"note": ""},
222
+ "gujarat": {"rate": 0.047, "reg": 0.01, "note": ""},
223
+ "rajasthan": {"rate": 0.06, "reg": 0.01, "note": ""},
224
+ "uttar_pradesh": {"rate": 0.07, "reg": 0.01, "note": ""},
225
+ "west_bengal": {"rate": 0.07, "reg": 0.01, "note": ""},
226
+ "generic": {"rate": 0.06, "reg": 0.01, "note": "Generic — verify specific state"},
227
+ }
228
+
229
+
230
+ def calc_india(price, state):
231
+ sk = state.lower().replace(" ", "_")
232
+ sd = INDIA_RATES.get(sk, INDIA_RATES["generic"])
233
+ stamp = price * sd["rate"]
234
+ reg = price * sd["reg"]
235
+ return {
236
+ "country": "India", "state": state, "price_inr": price,
237
+ "taxes": {
238
+ "stamp_duty": {"amount": round(stamp), "rate": f"{sd['rate']*100:.1f}%", "note": sd["note"]},
239
+ "registration_fee": {"amount": round(reg), "rate": f"{sd['reg']*100:.1f}%"},
240
+ },
241
+ "total_buyer": round(stamp + reg),
242
+ "total_pct": f"{(stamp+reg)/price*100:.2f}%",
243
+ "circle_rate_warning": (
244
+ "CRITICAL: If circle rate > transaction price, stamp duty is on circle rate. "
245
+ "Also triggers Sec.50C (seller deemed consideration) and Sec.56(2)(x) (buyer deemed income) if diff > INR 50,000."
246
+ ),
247
+ "tds_194ia": "If price > INR 50 lakhs: buyer deducts 1% TDS via Form 26QB within 30 days. Buyer is assessee-in-default if not done.",
248
+ "disclaimer": "ESTIMATE ONLY. Rates change annually per state. Verify with local advocate before registration.",
249
+ }
250
+
251
+
252
+ # ─── UAE ──────────────────────────────────────────────────────────────────────
253
+
254
+ def calc_uae(price, emirate):
255
+ rates = {
256
+ "dubai": {"dld": 0.04, "note": "DLD 4%; typically split 2% buyer + 2% seller"},
257
+ "abu_dhabi": {"dld": 0.02, "note": "Abu Dhabi registration fee 2%"},
258
+ "sharjah": {"dld": 0.04, "note": ""},
259
+ "ras_al_khaimah":{"dld": 0.02, "note": ""},
260
+ "generic": {"dld": 0.04, "note": "Generic UAE — verify specific emirate"},
261
+ }
262
+ ek = emirate.lower().replace(" ", "_")
263
+ rd = rates.get(ek, rates["generic"])
264
+ dld = price * rd["dld"]
265
+ return {
266
+ "country": "UAE", "emirate": emirate, "price_aed": price,
267
+ "taxes": {
268
+ "DLD_transfer_fee": {"amount": round(dld), "rate": f"{rd['dld']*100:.0f}%", "note": rd["note"]},
269
+ "trustee_office_fee": "AED 4,000 (properties > AED 500K)",
270
+ "agency_fee_typical": "2% of price (negotiable)",
271
+ },
272
+ "total_government_fees_approx": round(dld + 4000),
273
+ "no_cgt": "UAE imposes no capital gains tax on property disposals for individuals.",
274
+ "freehold_note": "Foreign buyers restricted to designated freehold zones only.",
275
+ "vat_note": "Commercial sale/lease: 5% VAT. Residential: exempt.",
276
+ "disclaimer": "ESTIMATE ONLY. Verify current DLD fees with DLD or registered trustee.",
277
+ }
278
+
279
+
280
+ # ─── GERMANY ──────────────────────────────────────────────────────────────────
281
+
282
+ GERMANY_GRESTS = {
283
+ "bavaria": 0.035, "sachsen": 0.035, "hamburg": 0.045, "bremen": 0.05,
284
+ "berlin": 0.06, "hessen": 0.06, "mecklenburg_vorpommern": 0.06,
285
+ "sachsen_anhalt": 0.05, "schleswig_holstein": 0.065, "brandenburg": 0.065,
286
+ "thuringen": 0.065, "nordrhein_westfalen": 0.065, "saarland": 0.065,
287
+ "rheinland_pfalz": 0.05, "niedersachsen": 0.05, "baden_wurttemberg": 0.05,
288
+ "default": 0.05,
289
+ }
290
+
291
+
292
+ def calc_germany(price, bundesland):
293
+ lk = bundesland.lower().replace(" ", "_")
294
+ rate = GERMANY_GRESTS.get(lk, GERMANY_GRESTS["default"])
295
+ grests = price * rate
296
+ notary = price * 0.015
297
+ return {
298
+ "country": "Germany", "bundesland": bundesland, "price_eur": price,
299
+ "taxes": {
300
+ "Grunderwerbsteuer_GrESt": {"amount": round(grests), "rate": f"{rate*100:.1f}%"},
301
+ "notary_and_land_registry_approx": {"amount": round(notary), "rate": "~1.5%"},
302
+ },
303
+ "total_buyer_approx": round(grests + notary),
304
+ "share_deal_warning": "GrESt triggers if >=90% of shares in property-owning company acquired (post-2021). Get specialist advice.",
305
+ "speculation_tax": "Individuals: capital gain taxed as ordinary income if sold within 10 years of purchase. Exempt after 10 years.",
306
+ "disclaimer": "ESTIMATE ONLY. GrESt varies by Bundesland. Verify with German Notar.",
307
+ }
308
+
309
+
310
+ # ─── FRANCE ───────────────────────────────────────────────────────────────────
311
+
312
+ def calc_france(price, is_new):
313
+ if is_new:
314
+ tva = price * 0.20
315
+ droits = price * 0.00715
316
+ notary = price * 0.008
317
+ return {
318
+ "country": "France", "transaction_type": "New build (VEFA)", "price_eur": price,
319
+ "taxes": {
320
+ "TVA": {"amount": round(tva), "rate": "20%", "note": "10% possible for some affordable housing"},
321
+ "Droits_de_mutation_reduced": {"amount": round(droits), "rate": "0.715%"},
322
+ "Notary_fees_approx": {"amount": round(notary), "rate": "~0.8%"},
323
+ },
324
+ "total_buyer_approx": round(tva + droits + notary),
325
+ "disclaimer": "ESTIMATE ONLY. Verify with French notaire.",
326
+ }
327
+ else:
328
+ droits = price * 0.057
329
+ notary = price * 0.008
330
+ return {
331
+ "country": "France", "transaction_type": "Resale (revente)", "price_eur": price,
332
+ "taxes": {
333
+ "Droits_de_mutation": {"amount": round(droits), "rate": "~5.7-5.8%",
334
+ "note": "Departmental 4.5% + communal 1.2% + national 0.1%"},
335
+ "Notary_fees_approx": {"amount": round(notary), "rate": "~0.8%"},
336
+ },
337
+ "total_buyer_approx": round(droits + notary),
338
+ "plus_value_note": (
339
+ "Seller plus-value: 36.2% total (19% income + 17.2% social). "
340
+ "Abatements after 5 years. Full exemption: 22 years (income) / 30 years (social). "
341
+ "Principal residence always exempt."
342
+ ),
343
+ "disclaimer": "ESTIMATE ONLY. Verify with French notaire.",
344
+ }
345
+
346
+
347
+ # ─── CLI ──────────────────────────────────────────────────────────────────────
348
+
349
+ def main():
350
+ parser = argparse.ArgumentParser(description="Multi-jurisdiction property transfer tax estimator.")
351
+ parser.add_argument("--country", required=True,
352
+ choices=["spain", "uk", "usa", "india", "uae", "germany", "france"])
353
+ parser.add_argument("--value", type=float, required=True, help="Transaction price in local currency")
354
+ parser.add_argument("--buyer-type", default="resident", choices=["resident", "non_resident"])
355
+ parser.add_argument("--asset-type", default="residential", choices=["residential", "commercial", "industrial"])
356
+ parser.add_argument("--region", default="default", help="CCAA / state / Bundesland / emirate")
357
+ parser.add_argument("--is-new", action="store_true", help="New build (Spain, France)")
358
+ parser.add_argument("--additional-dwelling", action="store_true", help="Additional dwelling surcharge (UK +3%)")
359
+ args = parser.parse_args()
360
+
361
+ dispatch = {
362
+ "spain": lambda: calc_spain(args.value, args.buyer_type, args.asset_type, args.is_new, args.region),
363
+ "uk": lambda: calc_uk(args.value, args.buyer_type, args.asset_type, args.additional_dwelling),
364
+ "usa": lambda: calc_usa(args.value, args.region),
365
+ "india": lambda: calc_india(args.value, args.region),
366
+ "uae": lambda: calc_uae(args.value, args.region if args.region != "default" else "dubai"),
367
+ "germany": lambda: calc_germany(args.value, args.region),
368
+ "france": lambda: calc_france(args.value, args.is_new),
369
+ }
370
+ result = dispatch[args.country]()
371
+ print(json.dumps(result, indent=2, ensure_ascii=False))
372
+
373
+
374
+ if __name__ == "__main__":
375
+ main()
scripts/validate_tax.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ validate_tax.py — Tax compliance checklist generator by jurisdiction and transaction type.
4
+
5
+ Usage:
6
+ python scripts/validate_tax.py --jurisdiction spain --transaction sale --value 2500000
7
+ python scripts/validate_tax.py --jurisdiction uk --transaction sale --entity-type company
8
+ python scripts/validate_tax.py --jurisdiction usa --transaction sale --value 3000000
9
+ python scripts/validate_tax.py --jurisdiction india --transaction sale --value 15000000
10
+ python scripts/validate_tax.py --jurisdiction spain --transaction lease
11
+
12
+ Output:
13
+ JSON checklist of tax obligations with DONE/PENDING/NA status fields,
14
+ deadlines, sanctions for non-compliance, and responsible party.
15
+
16
+ This script generates the checklist structure. The agent marks each item
17
+ as DONE / PENDING / NA based on information provided by the user.
18
+
19
+ IMPORTANT: This is a framework for analysis — not tax advice. Verify all
20
+ obligations with qualified local tax counsel before any transaction.
21
+ """
22
+
23
+ import argparse
24
+ import json
25
+ import sys
26
+
27
+ # ─── Checklist Templates ───────────────────────────────────────────────────────
28
+
29
+ CHECKLISTS = {
30
+
31
+ # ── SPAIN — SALE ──────────────────────────────────────────────────────────
32
+ "spain_sale": {
33
+ "title": "Tax Compliance Checklist — Spain Property Sale / Compraventa",
34
+ "jurisdiction_label": "Spain — Análisis bajo ley española",
35
+ "reference": "references/countries/eu/spain/tax-law.md",
36
+ "items": [
37
+ {
38
+ "id": "ES-S01", "obligado": "Buyer / Comprador",
39
+ "item": "ITP_or_IVA_calculated_on_correct_base",
40
+ "desc": (
41
+ "Determine if ITP (resale) or IVA+AJD (new build) applies — they are MUTUALLY EXCLUSIVE. "
42
+ "Calculate on higher of: transaction price or valor de referencia catastral. "
43
+ "ITP rate: 6-10% depending on CCAA (Madrid 6%, Cataluña 10%, Baleares 11%)."
44
+ ),
45
+ "deadline": "Autoliquidación within 30 days of deed (escritura)",
46
+ "sanction": "Instrument inadmissible in court; AEAT demand + interest 3.75%/yr + penalty 50-150% of unpaid",
47
+ "status": "PENDING",
48
+ },
49
+ {
50
+ "id": "ES-S02", "obligado": "Buyer / Comprador",
51
+ "item": "AJD_autoliquidated",
52
+ "desc": (
53
+ "AJD (Actos Jurídicos Documentados) cuota gradual if deed is a public notarial document. "
54
+ "Rate: 0.5-2% depending on CCAA (Madrid 0.75%, Valencia 2.0%). "
55
+ "Paid separately from ITP."
56
+ ),
57
+ "deadline": "Within 30 days of deed",
58
+ "sanction": "Surcharge 5-20% + interest if late; penalty if not filed",
59
+ "status": "PENDING",
60
+ },
61
+ {
62
+ "id": "ES-S03", "obligado": "Seller / Vendedor",
63
+ "item": "plusvalia_municipal_IIVTNU_calculated_and_paid",
64
+ "desc": (
65
+ "Calculate IIVTNU by BOTH methods (STC TC 26/2021 — mandatory): "
66
+ "(1) Objective method: cadastral land value × coefficient × municipal rate. "
67
+ "(2) Real method: (sale price of land portion) − (acquisition price of land portion). "
68
+ "Use whichever is MORE FAVOURABLE to the taxpayer. "
69
+ "If land has lost value: no tax due (STC TC 59/2017). "
70
+ "Pay to the municipality where the property is located."
71
+ ),
72
+ "deadline": "30 days from deed date (inter vivos); 6 months (mortis causa)",
73
+ "sanction": "Penalty 50-150% of unpaid + interest; criminal prosecution if fraudulent",
74
+ "status": "PENDING",
75
+ },
76
+ {
77
+ "id": "ES-S04", "obligado": "Buyer / Comprador (if seller is non-resident)",
78
+ "item": "non_resident_seller_3pct_retention_via_modelo_211",
79
+ "desc": (
80
+ "MANDATORY if seller is non-resident (regardless of nationality or country of residence): "
81
+ "Buyer withholds 3% of the TOTAL SALE PRICE (not of the gain) and remits via "
82
+ "Modelo 211 within 30 days of the deed. "
83
+ "Legal basis: IRNR Art.25.2 LIRNR. "
84
+ "If buyer does NOT withhold: buyer is jointly liable (responsable solidario) "
85
+ "for the seller's IRNR on the capital gain. "
86
+ "Seller can claim refund if IRNR on actual gain < 3% retention."
87
+ ),
88
+ "deadline": "30 days from escritura (deed date)",
89
+ "sanction": "Buyer jointly liable for full IRNR + interest + penalty if not withheld",
90
+ "status": "PENDING",
91
+ },
92
+ {
93
+ "id": "ES-S05", "obligado": "Seller / Vendedor",
94
+ "item": "IRPF_or_IRNR_capital_gain_declared",
95
+ "desc": (
96
+ "IRPF (resident) or IRNR (non-resident) on the capital gain. "
97
+ "IRPF savings rate: 19% (up to EUR 6K), 21% (6K-50K), 23% (50K-200K), "
98
+ "27% (200K-300K), 28% (over EUR 300K). "
99
+ "Exemptions to check: (1) Over-65 selling main residence — fully exempt. "
100
+ "(2) Reinvestment in main residence — exempt pro-rata (Art.38 LIRPF). "
101
+ "IRNR (non-resident): 19% EU/EEA residents; 24% all others. "
102
+ "IRNR non-residents file Modelo 210 within 30 days of deed."
103
+ ),
104
+ "deadline": "IRPF: annual return (Apr-Jun following year). IRNR: 30 days from deed.",
105
+ "sanction": "Interest 3.75%/yr + penalty 50-150% of unpaid tax",
106
+ "status": "PENDING",
107
+ },
108
+ {
109
+ "id": "ES-S06", "obligado": "Both parties",
110
+ "item": "deed_registered_at_registro_de_propiedad",
111
+ "desc": (
112
+ "Escritura pública registered at the Registro de la Propiedad. "
113
+ "Without registration: transaction is not enforceable against third parties. "
114
+ "Registrar will reject if taxes not paid (ITP/AJD self-assessment must be presented)."
115
+ ),
116
+ "deadline": "No statutory deadline but critical for security",
117
+ "sanction": "Inoponibilidad frente a terceros — deal can be overridden by later registered transaction",
118
+ "status": "PENDING",
119
+ },
120
+ {
121
+ "id": "ES-S07", "obligado": "Buyer / Comprador",
122
+ "item": "catastro_ownership_change_communicated",
123
+ "desc": (
124
+ "Buyer must communicate the ownership change to the Catastro within 2 months "
125
+ "of the deed. Usually handled by the notary (notificación automática) — confirm."
126
+ ),
127
+ "deadline": "2 months from escritura",
128
+ "sanction": "Multa by Catastro for non-communication",
129
+ "status": "PENDING",
130
+ },
131
+ ],
132
+ },
133
+
134
+ # ── UK — SALE ─────────────────────────────────────────────────────────────
135
+ "uk_sale": {
136
+ "title": "Tax Compliance Checklist — UK Property Sale",
137
+ "jurisdiction_label": "United Kingdom — Analysis under UK law",
138
+ "reference": "references/countries/uk/tax-law.md",
139
+ "items": [
140
+ {
141
+ "id": "UK-S01", "obligado": "Buyer (England/NI)",
142
+ "item": "SDLT_return_filed_and_paid",
143
+ "desc": (
144
+ "SDLT1 return filed with HMRC and Stamp Duty Land Tax paid. "
145
+ "Residential rates: 0% up to GBP 250K; 5% (250K-925K); 10% (925K-1.5M); 12% above. "
146
+ "Non-residential: 0% up to GBP 150K; 2% (150K-250K); 5% above. "
147
+ "Surcharges: +3% additional dwelling; +2% non-resident buyer. "
148
+ "Scotland: use LBTT (Revenue Scotland). Wales: use LTT (Welsh Revenue Authority)."
149
+ ),
150
+ "deadline": "14 DAYS from completion — SDLT Act 2003 s.76. NO EXTENSIONS.",
151
+ "sanction": "Day 1: GBP 100 automatic. Day 91: GBP 200. 12 months: GBP 300 or 5% of SDLT. Interest accrues daily.",
152
+ "status": "PENDING",
153
+ },
154
+ {
155
+ "id": "UK-S02", "obligado": "Seller (residential property)",
156
+ "item": "CGT_reported_and_paid_within_60_days",
157
+ "desc": (
158
+ "CGT on UK residential property MUST be reported and initial payment made within "
159
+ "60 days of completion via HMRC's UK Property Account (online portal). "
160
+ "Rates: 18% (basic rate) / 28% (higher rate). Annual exempt amount: GBP 3,000. "
161
+ "PPR relief if main residence. "
162
+ "Non-residents: same 60-day rule applies (since April 2020). "
163
+ "Commercial property CGT: reported via self-assessment return — no 60-day rule."
164
+ ),
165
+ "deadline": "60 days from completion date",
166
+ "sanction": "GBP 100 late filing penalty + interest on unpaid CGT from due date",
167
+ "status": "PENDING",
168
+ },
169
+ {
170
+ "id": "UK-S03", "obligado": "Company owner (if applicable)",
171
+ "item": "ATED_return_if_company_holds_residential",
172
+ "desc": (
173
+ "Annual Tax on Enveloped Dwellings (ATED) applies if a company holds UK residential "
174
+ "property worth more than GBP 500,000. "
175
+ "Annual return due 30 April. Payment due 30 April. "
176
+ "Multiple reliefs available — must be claimed on return (not automatic). "
177
+ "Relief: property let to unconnected tenant at arm's length."
178
+ ),
179
+ "deadline": "30 April each tax year",
180
+ "sanction": "Daily penalties + interest. Criminal prosecution in serious cases.",
181
+ "status": "PENDING",
182
+ },
183
+ {
184
+ "id": "UK-S04", "obligado": "Seller (commercial property)",
185
+ "item": "VAT_option_to_tax_checked",
186
+ "desc": (
187
+ "Check if seller has opted to tax (OTT) the property. "
188
+ "If OTT in place: 20% VAT charged on sale price — buyer must be able to recover. "
189
+ "Transfer of Going Concern (TOGC): may disapply VAT if conditions met "
190
+ "(both parties VAT-registered, property let, buyer adopts OTT). "
191
+ "Check with seller's solicitor and accountant."
192
+ ),
193
+ "deadline": "Before exchange of contracts",
194
+ "sanction": "Incorrect VAT treatment leads to HMRC assessment, interest and penalties",
195
+ "status": "PENDING",
196
+ },
197
+ {
198
+ "id": "UK-S05", "obligado": "Seller (if non-resident)",
199
+ "item": "NRCGT_reported_if_non_resident",
200
+ "desc": (
201
+ "Non-Resident Capital Gains Tax (NRCGT): non-UK residents subject to CGT on "
202
+ "UK property gains since April 2015 (residential) and April 2019 (commercial). "
203
+ "Same 60-day reporting requirement as UK residents. "
204
+ "Rates same as residents. File via HMRC UK Property Account."
205
+ ),
206
+ "deadline": "60 days from completion",
207
+ "sanction": "Same as UK residents: GBP 100 penalty + interest",
208
+ "status": "PENDING",
209
+ },
210
+ ],
211
+ },
212
+
213
+ # ── USA — SALE ────────────────────────────────────────────────────────────
214
+ "usa_sale": {
215
+ "title": "Tax Compliance Checklist — US Property Sale",
216
+ "jurisdiction_label": "USA — Analysis under US federal law (state taxes vary)",
217
+ "reference": "references/countries/usa/tax-law.md",
218
+ "items": [
219
+ {
220
+ "id": "US-S01", "obligado": "Buyer / Closing Agent",
221
+ "item": "state_transfer_tax_paid_at_closing",
222
+ "desc": (
223
+ "State and local transfer taxes paid at closing. "
224
+ "Rates vary dramatically: Texas 0%; California ~0.11%; Florida 0.7%; "
225
+ "New York State 0.4% + NYC 1-2.075% + Mansion Tax if >= USD 1M. "
226
+ "VERIFY specific state, county, and municipal rates with local counsel."
227
+ ),
228
+ "deadline": "At closing — must be paid before deed recorded",
229
+ "sanction": "Deed not recorded; title defect; lender cannot fund",
230
+ "status": "PENDING",
231
+ },
232
+ {
233
+ "id": "US-S02", "obligado": "Seller (if pursuing 1031 exchange)",
234
+ "item": "1031_QI_designated_before_closing",
235
+ "desc": (
236
+ "Section 1031 Like-Kind Exchange: Qualified Intermediary (QI) MUST be designated "
237
+ "and exchange agreement signed BEFORE the relinquished property closing. "
238
+ "Seller CANNOT receive, control, or pledge sale proceeds — QI holds them directly. "
239
+ "If seller touches funds even briefly: exchange FAILS and full gain is taxable."
240
+ ),
241
+ "deadline": "QI engaged BEFORE closing — no exceptions",
242
+ "sanction": "Exchange fails; entire capital gain taxable in year of sale + potential underpayment penalty",
243
+ "status": "PENDING",
244
+ },
245
+ {
246
+ "id": "US-S03", "obligado": "Seller (if pursuing 1031 exchange)",
247
+ "item": "1031_45_day_identification_window",
248
+ "desc": (
249
+ "Replacement property must be IDENTIFIED IN WRITING to the QI within 45 CALENDAR "
250
+ "DAYS of the relinquished property closing. "
251
+ "Rules: 3-Property Rule (identify up to 3 properties, any value), OR "
252
+ "200% Rule (any number of properties, total value ≤ 200% of relinquished), OR "
253
+ "95% Rule (any number if 95% actually acquired). "
254
+ "45-day window is ABSOLUTE — no extensions (except presidentially-declared disasters)."
255
+ ),
256
+ "deadline": "45 calendar days from relinquished property closing",
257
+ "sanction": "Exchange fails; entire gain taxable if identification deadline missed",
258
+ "status": "PENDING",
259
+ },
260
+ {
261
+ "id": "US-S04", "obligado": "Seller (if pursuing 1031 exchange)",
262
+ "item": "1031_180_day_closing_window",
263
+ "desc": (
264
+ "Replacement property must be ACQUIRED (closed) within 180 CALENDAR DAYS of the "
265
+ "relinquished property closing, OR by the tax return due date (including extensions) "
266
+ "— whichever is EARLIER. "
267
+ "If tax return due before 180 days: file for extension to preserve 180 days."
268
+ ),
269
+ "deadline": "180 calendar days from relinquished property closing (earlier if tax return due sooner)",
270
+ "sanction": "Exchange fails if closing window missed; full gain taxable",
271
+ "status": "PENDING",
272
+ },
273
+ {
274
+ "id": "US-S05", "obligado": "Buyer (if seller is foreign person)",
275
+ "item": "FIRPTA_withholding_15pct",
276
+ "desc": (
277
+ "FIRPTA: if seller is a 'foreign person' (non-US citizen non-resident, foreign corporation, etc.), "
278
+ "buyer must withhold 15% of the AMOUNT REALIZED (not the gain). "
279
+ "File Form 8288 (and copy A of 8288-A) and remit withheld amount to IRS. "
280
+ "Exceptions: (1) Amount realized ≤ USD 300K AND buyer will use as residence = 0%. "
281
+ "(2) USD 300K-1M AND buyer residence use = 10%. "
282
+ "(3) Seller provides withholding certificate (Form 8288-B)."
283
+ ),
284
+ "deadline": "Form 8288 filed and tax paid within 20 days of closing",
285
+ "sanction": "Buyer becomes personally liable for seller's US tax + interest + penalties",
286
+ "status": "PENDING",
287
+ },
288
+ {
289
+ "id": "US-S06", "obligado": "Seller",
290
+ "item": "depreciation_recapture_Sec1250_calculated",
291
+ "desc": (
292
+ "Unrecaptured Section 1250 gain (depreciation recapture) taxed at maximum 25% — "
293
+ "separate from the general long-term capital gains rate. "
294
+ "Applies to all commercial real property with accumulated depreciation. "
295
+ "Calculate: total depreciation taken over holding period = recapture amount. "
296
+ "Cannot be deferred in a 1031 exchange (recapture is still deferred in 1031)."
297
+ ),
298
+ "deadline": "Tax return for the year of sale",
299
+ "sanction": "Underpayment penalty + interest on unpaid recapture tax",
300
+ "status": "PENDING",
301
+ },
302
+ ],
303
+ },
304
+
305
+ # ── INDIA — SALE ──────────────────────────────────────────────────────────
306
+ "india_sale": {
307
+ "title": "Tax Compliance Checklist — India Property Sale",
308
+ "jurisdiction_label": "India — Analysis under Indian law (Income Tax Act 1961, state stamp duty laws)",
309
+ "reference": "references/countries/india/tax-law.md",
310
+ "items": [
311
+ {
312
+ "id": "IN-S01", "obligado": "Seller / Vendedor",
313
+ "item": "capital_gains_LTCG_STCG_computed",
314
+ "desc": (
315
+ "Determine LTCG (held > 24 months) or STCG (held ≤ 24 months). "
316
+ "LTCG rate: 12.5% without indexation (Finance Act 2024 — verify current position). "
317
+ "STCG: taxed at applicable slab rate. "
318
+ "Exemptions to check: Sec.54 (reinvest in residential — max INR 10Cr), "
319
+ "Sec.54F (reinvest from any asset), Sec.54EC (bonds — max INR 50L within 6 months). "
320
+ "CGAS deposit if reinvestment not done by tax return due date."
321
+ ),
322
+ "deadline": "Advance tax quarterly; final settlement in annual return",
323
+ "sanction": "Interest u/s 234B/234C + penalty if concealed",
324
+ "status": "PENDING",
325
+ },
326
+ {
327
+ "id": "IN-S02", "obligado": "Buyer / Purchaser",
328
+ "item": "TDS_194IA_deducted_and_Form_26QB_filed",
329
+ "desc": (
330
+ "Section 194-IA: if consideration > INR 50 lakhs, buyer MUST deduct TDS at 1% "
331
+ "and deposit via Form 26QB online within 30 days. "
332
+ "Issue Form 16B to seller within 15 days of deposit. "
333
+ "Note: TDS is on TOTAL consideration, not just the portion above 50L. "
334
+ "Non-deduction: buyer is assessee-in-default — liable for TDS amount + interest 1%/month + penalty equal to TDS."
335
+ ),
336
+ "deadline": "Form 26QB within 30 days of month-end in which deduction made",
337
+ "sanction": "Assessee-in-default; interest 1%/month (non-deduction) or 1.5%/month (non-payment) + equal penalty",
338
+ "status": "PENDING",
339
+ },
340
+ {
341
+ "id": "IN-S03", "obligado": "Buyer / Purchaser",
342
+ "item": "stamp_duty_and_registration_completed",
343
+ "desc": (
344
+ "Stamp duty paid at state-specific rate (4-8%) on the HIGHER of: "
345
+ "transaction value or circle rate (ready reckoner rate). "
346
+ "Document registered at Sub-Registrar Office. "
347
+ "If circle rate > transaction price: Sec.50C applies to seller (deemed consideration), "
348
+ "and Sec.56(2)(x) may apply to buyer (deemed income if difference > INR 50K)."
349
+ ),
350
+ "deadline": "Before or at time of registration (must be done on day of execution or within statutory period)",
351
+ "sanction": "Instrument inadmissible; document not accepted by Sub-Registrar; penalty for under-stamping",
352
+ "status": "PENDING",
353
+ },
354
+ {
355
+ "id": "IN-S04", "obligado": "Seller / Vendedor",
356
+ "item": "Section_50C_circle_rate_checked",
357
+ "desc": (
358
+ "Section 50C: if circle rate > transaction price, capital gains computed on circle rate. "
359
+ "Remedy: obtain certificate from registered valuer (Sec.50C(2) proviso) if actual FMV < circle rate. "
360
+ "Threshold: no deemed consideration if circle rate ≤ 110% of transaction price (safe harbour). "
361
+ "If circle rate > 110% of price: deemed consideration = circle rate."
362
+ ),
363
+ "deadline": "Before signing sale deed",
364
+ "sanction": "Capital gains computed on higher circle rate; phantom income taxed",
365
+ "status": "PENDING",
366
+ },
367
+ {
368
+ "id": "IN-S05", "obligado": "Both parties (if NRI/foreign entity involved)",
369
+ "item": "FEMA_compliance_verified",
370
+ "desc": (
371
+ "FEMA: NRI/OCI can purchase residential or commercial property (not agricultural/plantation/farmhouse) "
372
+ "without RBI approval. Foreign companies/entities: case-by-case RBI approval required. "
373
+ "Repatriation: up to 2 residential properties; proceeds from original remittance. "
374
+ "Reporting: AD Bank must be notified. TRC and Tax Residency Certificate required for DTAA benefits."
375
+ ),
376
+ "deadline": "Before transaction",
377
+ "sanction": "FEMA contravention: compounding fine up to 3× the transaction amount; criminal prosecution in serious cases",
378
+ "status": "PENDING",
379
+ },
380
+ ],
381
+ },
382
+
383
+ # ── SPAIN — LEASE ─────────────────────────────────────────────────────────
384
+ "spain_lease": {
385
+ "title": "Tax Compliance Checklist — Spain Commercial Lease (Ongoing)",
386
+ "jurisdiction_label": "Spain — Análisis bajo ley española",
387
+ "reference": "references/countries/eu/spain/tax-law.md",
388
+ "items": [
389
+ {
390
+ "id": "ES-L01", "obligado": "Landlord / Arrendador",
391
+ "item": "IVA_21pct_on_commercial_rent_charged_and_declared",
392
+ "desc": (
393
+ "IVA at 21% on all commercial rent (uso distinto a vivienda). "
394
+ "Landlord must be registered for IVA (Modelo 036/037). "
395
+ "Issue factura with IVA to tenant each rental period. "
396
+ "File quarterly Modelo 303; annual Modelo 390 summary. "
397
+ "Tenant recovers IVA as input tax if VAT-registered."
398
+ ),
399
+ "deadline": "Quarterly declarations: April 20, July 20, October 20, January 30",
400
+ "sanction": "AEAT demand for uncharge IVA + interest 3.75%/yr + penalty 50-150%",
401
+ "status": "PENDING",
402
+ },
403
+ {
404
+ "id": "ES-L02", "obligado": "Tenant / Arrendatario (if company or professional)",
405
+ "item": "IRPF_19pct_retention_applied",
406
+ "desc": (
407
+ "If tenant is a company (sociedad) or self-employed professional (autónomo), "
408
+ "tenant must withhold IRPF retention of 19% from the rent and remit via "
409
+ "Modelo 115 each quarter. "
410
+ "Exception: tenant who is a private individual (persona física no empresaria) — "
411
+ "no retention obligation. "
412
+ "Annual summary: Modelo 180."
413
+ ),
414
+ "deadline": "Quarterly Modelo 115: April 20, July 20, October 20, January 30",
415
+ "sanction": "Tenant is assessee-in-default for unretained amount + interest + penalty",
416
+ "status": "PENDING",
417
+ },
418
+ {
419
+ "id": "ES-L03", "obligado": "Landlord / Arrendador",
420
+ "item": "IBI_Impuesto_Bienes_Inmuebles_current",
421
+ "desc": (
422
+ "IBI (Impuesto sobre Bienes Inmuebles) paid to municipality. "
423
+ "Typically debited directly by municipality in August-November. "
424
+ "Arrears on IBI create a real charge (carga real) on the property — "
425
+ "buyer acquires property encumbered with IBI arrears. "
426
+ "Always request IBI certification from municipality before any transaction."
427
+ ),
428
+ "deadline": "Per municipal calendar (usually August-November voluntary period)",
429
+ "sanction": "Surcharge + interest; municipal enforcement proceedings; property charge",
430
+ "status": "PENDING",
431
+ },
432
+ ],
433
+ },
434
+
435
+ # ── UK — LEASE ────────────────────────────────────────────────────────────
436
+ "uk_lease": {
437
+ "title": "Tax Compliance Checklist — UK Commercial Lease (Ongoing)",
438
+ "jurisdiction_label": "United Kingdom — Analysis under UK law",
439
+ "reference": "references/countries/uk/tax-law.md",
440
+ "items": [
441
+ {
442
+ "id": "UK-L01", "obligado": "Landlord",
443
+ "item": "SDLT_on_lease_premium_and_or_NPV_of_rent",
444
+ "desc": (
445
+ "SDLT may be due on: (1) any premium paid for the lease, AND (2) the NPV of rent "
446
+ "if it exceeds GBP 150,000 (non-residential). "
447
+ "Calculate NPV of rent over lease term using HMRC formula. "
448
+ "SDLT on NPV: 0% up to GBP 150K; 1% above GBP 150K (non-residential). "
449
+ "File SDLT1 return within 14 days of lease commencement."
450
+ ),
451
+ "deadline": "14 days from lease effective date",
452
+ "sanction": "Same as purchase SDLT penalties — GBP 100 day 1, escalating",
453
+ "status": "PENDING",
454
+ },
455
+ {
456
+ "id": "UK-L02", "obligado": "Landlord",
457
+ "item": "VAT_on_rent_if_OTT_in_place",
458
+ "desc": (
459
+ "If landlord has opted to tax (OTT) the property: 20% VAT charged on rent. "
460
+ "VAT invoices must be issued; quarterly VAT returns filed. "
461
+ "If no OTT: rental is exempt — no VAT charged and no input VAT recovery on costs. "
462
+ "OTT decision is irrevocable for 20 years (except in first 6 months)."
463
+ ),
464
+ "deadline": "Quarterly VAT returns",
465
+ "sanction": "HMRC assessment for VAT not charged + interest + penalties",
466
+ "status": "PENDING",
467
+ },
468
+ {
469
+ "id": "UK-L03", "obligado": "Landlord",
470
+ "item": "rental_income_reported_for_income_tax_or_corporation_tax",
471
+ "desc": (
472
+ "Individual landlord: rental profits taxed as income (20/40/45%). "
473
+ "Finance cost restriction: mortgage interest restricted to basic rate (20%) relief. "
474
+ "Company landlord: Corporation Tax at 25% (profits > GBP 250K). "
475
+ "Non-resident landlord: 20% withheld by agent/tenant unless HMRC exemption granted (NRLS)."
476
+ ),
477
+ "deadline": "Self-assessment: 31 January following tax year-end",
478
+ "sanction": "Automatic penalties + interest on unpaid tax",
479
+ "status": "PENDING",
480
+ },
481
+ ],
482
+ },
483
+ }
484
+
485
+ # ─── Helper ────────────────────────────────────────────────────────────────────
486
+
487
+ def get_checklist(jurisdiction: str, transaction: str, value=None, entity_type="individual") -> dict:
488
+ key = f"{jurisdiction}_{transaction}"
489
+ if key not in CHECKLISTS:
490
+ available = list(CHECKLISTS.keys())
491
+ return {
492
+ "error": f"No checklist found for jurisdiction='{jurisdiction}' transaction='{transaction}'.",
493
+ "available_combinations": available,
494
+ "add_instruction": f"To add: create CHECKLISTS['{key}'] in scripts/validate_tax.py",
495
+ }
496
+ cl = CHECKLISTS[key]
497
+ return {
498
+ "jurisdiction": jurisdiction,
499
+ "transaction": transaction,
500
+ "entity_type": entity_type,
501
+ "value": value,
502
+ "title": cl["title"],
503
+ "jurisdiction_label": cl["jurisdiction_label"],
504
+ "reference_file": cl["reference"],
505
+ "item_count": len(cl["items"]),
506
+ "items": cl["items"],
507
+ "instructions": (
508
+ "Mark each item STATUS as: DONE (confirmed compliant) / PENDING (action required) / NA (not applicable). "
509
+ "All PENDING items require action before closing or within stated deadline."
510
+ ),
511
+ "disclaimer": (
512
+ "This checklist is a structured framework for analysis only. "
513
+ "It does not constitute tax advice. "
514
+ "Verify all obligations with qualified local tax counsel before any transaction."
515
+ ),
516
+ }
517
+
518
+
519
+ # ─── CLI ──────────────────────────────────────────────────────────────────────
520
+
521
+ def main():
522
+ parser = argparse.ArgumentParser(
523
+ description="Tax compliance checklist generator by jurisdiction and transaction type."
524
+ )
525
+ parser.add_argument(
526
+ "--jurisdiction", required=True,
527
+ choices=["spain", "uk", "usa", "india", "uae", "france", "germany"],
528
+ help="Country jurisdiction",
529
+ )
530
+ parser.add_argument(
531
+ "--transaction", required=True,
532
+ choices=["sale", "lease", "purchase", "development", "refinancing"],
533
+ help="Transaction type",
534
+ )
535
+ parser.add_argument(
536
+ "--value", type=float, default=None,
537
+ help="Transaction value in local currency (optional — for context)",
538
+ )
539
+ parser.add_argument(
540
+ "--entity-type", default="individual",
541
+ choices=["individual", "company", "non_resident", "reit", "trust", "nri", "foreign_entity"],
542
+ help="Entity type of the principal party (default: individual)",
543
+ )
544
+ args = parser.parse_args()
545
+
546
+ result = get_checklist(args.jurisdiction, args.transaction, args.value, args.entity_type)
547
+ print(json.dumps(result, indent=2, ensure_ascii=False))
548
+
549
+
550
+ if __name__ == "__main__":
551
+ main()
scripts/validate_visado.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ validate_visado.py — Pre-Visa Document Validation v8
4
+ Agent: value.railnexus.io
5
+ Includes: ECM/599/2025 compliance, condicionantes/advertencias, quick/full check
6
+
7
+ Usage:
8
+ python scripts/validate_visado.py --type "valoracion_eco805" --colegio COAC --mode full
9
+ python scripts/validate_visado.py --type "proyecto_basico_ejecucion" --colegio COAC --mode quick
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import sys
15
+ from datetime import datetime
16
+
17
+ # ═══════════════════════════════════════════════════════════
18
+ # PROJECT TYPE DEFINITIONS
19
+ # ═══════════════════════════════════════════════════════════
20
+
21
+ PROJECT_TYPES = {
22
+ "anteproyecto": {
23
+ "label": "TIPO 1: Anteproyecto",
24
+ "checklist_file": "tipos-1-2-4-5-6-7-8.md",
25
+ "requires_cte_justification": False,
26
+ "requires_ref_catastral": False,
27
+ "presupuesto_level": "estimacion_global",
28
+ "requires_comunicacion_DO": False,
29
+ "requires_ess": False,
30
+ "requires_geotecnico": False,
31
+ "visado_obligatorio": False,
32
+ },
33
+ "proyecto_basico": {
34
+ "label": "TIPO 2: Proyecto Basico",
35
+ "checklist_file": "tipos-1-2-4-5-6-7-8.md",
36
+ "requires_cte_justification": "declaracion",
37
+ "requires_ref_catastral": True,
38
+ "presupuesto_level": "capitulos",
39
+ "requires_comunicacion_DO": False,
40
+ "requires_ess": False,
41
+ "requires_geotecnico": False,
42
+ "visado_obligatorio": False,
43
+ },
44
+ "proyecto_basico_ejecucion": {
45
+ "label": "TIPO 3: Proyecto Basico y de Ejecucion",
46
+ "checklist_file": "tipo3-proyecto-basico-ejecucion.md",
47
+ "requires_cte_justification": "justificacion_detallada",
48
+ "requires_ref_catastral": True,
49
+ "presupuesto_level": "partidas_capitulos",
50
+ "requires_comunicacion_DO": True,
51
+ "requires_ess": True,
52
+ "requires_geotecnico": True,
53
+ "visado_obligatorio": True,
54
+ },
55
+ "demolicion": {
56
+ "label": "TIPO 4: Proyecto de Demolicion",
57
+ "checklist_file": "tipos-1-2-4-5-6-7-8.md",
58
+ "requires_cte_justification": False,
59
+ "requires_ref_catastral": True,
60
+ "presupuesto_level": "partidas_capitulos",
61
+ "requires_comunicacion_DO": False,
62
+ "requires_ess": True,
63
+ "requires_geotecnico": False,
64
+ "requires_costes_referencia": False,
65
+ "requires_fotografias": True,
66
+ "visado_obligatorio": True,
67
+ },
68
+ "legalizacion": {
69
+ "label": "TIPO 5: Expediente de Legalizacion",
70
+ "checklist_file": "tipos-1-2-4-5-6-7-8.md",
71
+ "requires_cte_justification": "comprobacion_grado",
72
+ "requires_ref_catastral": True,
73
+ "presupuesto_level": "capitulos",
74
+ "requires_comunicacion_DO": False,
75
+ "requires_ess": False,
76
+ "requires_geotecnico": False,
77
+ "redaccion_pasado": True,
78
+ "titulo_expediente": True,
79
+ "visado_obligatorio": True,
80
+ },
81
+ "direccion_obra_cfo": {
82
+ "label": "TIPO 6: Direccion de Obra y CFO",
83
+ "checklist_file": "tipos-1-2-4-5-6-7-8.md",
84
+ "requires_cte_justification": False,
85
+ "requires_ref_catastral": True,
86
+ "presupuesto_level": None,
87
+ "requires_comunicacion_DO": True,
88
+ "deposito_obligatorio": True,
89
+ "visado_obligatorio": True,
90
+ },
91
+ "valoracion_eco805": {
92
+ "label": "TIPO 7: Valoracion / Tasacion (ECO/805 + ECM/599/2025)",
93
+ "checklist_file": "tipos-1-2-4-5-6-7-8.md",
94
+ "requires_cte_justification": False,
95
+ "requires_ref_catastral": True,
96
+ "normativa_especifica": ["eco-805.md", "ecm-599-2025.md"],
97
+ "requires_nota_simple": True,
98
+ "requires_catastro": True,
99
+ "requires_cee": True,
100
+ "ecm599_applies": True,
101
+ "visado_obligatorio": False,
102
+ },
103
+ "certificado_descriptivo": {
104
+ "label": "TIPO 8: Certificado Descriptivo / Antiguedad / AFO",
105
+ "checklist_file": "tipos-1-2-4-5-6-7-8.md",
106
+ "requires_cte_justification": False,
107
+ "requires_ref_catastral": True,
108
+ "visado_obligatorio": False,
109
+ },
110
+ }
111
+
112
+ # ═══════════════════════════════════════════════════════════
113
+ # ECM/599/2025 VALIDATION RULES
114
+ # ═══════════════════════════════════════════════════════════
115
+
116
+ ECM599_RULES = [
117
+ {
118
+ "id": "ECM-CEE-01",
119
+ "nombre": "CEE edificio terminado",
120
+ "severidad": "BLOQUEANTE",
121
+ "normativa": "ECM/599/2025 -> art. 8.1 ECO/805",
122
+ "regla": "Edificio terminado: CEE debidamente REGISTRADO obligatorio",
123
+ "condicion": "tipo_inmueble == 'terminado'",
124
+ },
125
+ {
126
+ "id": "ECM-CEE-02",
127
+ "nombre": "CEE edificio en construccion/proyecto",
128
+ "severidad": "BLOQUEANTE",
129
+ "normativa": "ECM/599/2025 -> art. 8.1 ECO/805",
130
+ "regla": "En construccion/proyecto: CEE + copia solicitud registro, datos coincidentes",
131
+ "condicion": "tipo_inmueble IN ['en_construccion','proyecto']",
132
+ },
133
+ {
134
+ "id": "ECM-CEE-03",
135
+ "nombre": "CEE ausente - controversia",
136
+ "severidad": "CONFIGURABLE",
137
+ "normativa": "ECM/599/2025 -> art. 8 ECO/805",
138
+ "regla": "Controversia sectorial: configurable como BLOQUEANTE o ADVERTENCIA por sociedad",
139
+ "nota": "Pendiente resolucion definitiva",
140
+ },
141
+ {
142
+ "id": "ECM-SUP-01",
143
+ "nombre": "Superficie util excluye exteriores",
144
+ "severidad": "BLOQUEANTE",
145
+ "normativa": "ECM/599/2025 -> art. 4 ECO/805",
146
+ "regla": "Terrazas, balcones y patios NO computan como superficie util",
147
+ },
148
+ {
149
+ "id": "ECM-SUP-02",
150
+ "nombre": "Justificacion superficie adoptada",
151
+ "severidad": "BLOQUEANTE_CONDICIONAL",
152
+ "normativa": "ECM/599/2025 -> art. 4 ECO/805",
153
+ "regla": "Si superficie != util comprobada, justificar expresamente",
154
+ },
155
+ {
156
+ "id": "ECM-SUP-03",
157
+ "nombre": "Tabla desglose superficies",
158
+ "severidad": "ADVERTENCIA",
159
+ "normativa": "ECM/599/2025 -> art. 5.1.d ECO/805",
160
+ "regla": "Tabla desglose superficies por espacios, cuerpos edificacion, zonas comunes, exteriores",
161
+ },
162
+ {
163
+ "id": "ECM-SUP-04",
164
+ "nombre": "Valoracion separada garajes/trasteros",
165
+ "severidad": "ADVERTENCIA",
166
+ "normativa": "ECM/599/2025 -> art. 5.1.d ECO/805",
167
+ "regla": "Garajes y trasteros valorados separadamente",
168
+ },
169
+ {
170
+ "id": "ECM-FORM-01",
171
+ "nombre": "Indice obligatorio",
172
+ "severidad": "ADVERTENCIA",
173
+ "normativa": "ECM/599/2025 -> art. 65.1.p ECO/805",
174
+ "regla": "Informe DEBE contener indice al inicio con numero de pagina",
175
+ },
176
+ {
177
+ "id": "ECM-FORM-02",
178
+ "nombre": "Firma electronica cualificada",
179
+ "severidad": "BLOQUEANTE",
180
+ "normativa": "ECM/599/2025 -> art. 64.c ECO/805",
181
+ "regla": "TODOS los firmantes: firma electronica cualificada. No manuscrita.",
182
+ },
183
+ {
184
+ "id": "ECM-FORM-03",
185
+ "nombre": "Vigencia 2 anios",
186
+ "severidad": "ADVERTENCIA",
187
+ "normativa": "ECM/599/2025 -> art. 4 ECO/805",
188
+ "regla": "Vigencia limitada a 2 anios para TODAS las finalidades",
189
+ },
190
+ {
191
+ "id": "ECM-TEST-01",
192
+ "nombre": "Fuente de cada testigo",
193
+ "severidad": "ADVERTENCIA",
194
+ "normativa": "ECM/599/2025 -> art. 22 ECO/805",
195
+ "regla": "Cada testigo: fuente identificada y trazable",
196
+ },
197
+ {
198
+ "id": "ECM-TEST-02",
199
+ "nombre": "Ponderacion justificada",
200
+ "severidad": "ADVERTENCIA",
201
+ "normativa": "ECM/599/2025 -> art. 22.1.d ECO/805",
202
+ "regla": "Si pondera testigos: justificar cada ponderacion",
203
+ },
204
+ {
205
+ "id": "ECM-TEST-03",
206
+ "nombre": "Tipo homogeneizacion indicado",
207
+ "severidad": "ADVERTENCIA",
208
+ "normativa": "ECM/599/2025 -> art. 22.1.d ECO/805",
209
+ "regla": "Indicar si homogeneiza valor unitario o total. Coeficiente corrector si sup != util",
210
+ },
211
+ {
212
+ "id": "ECM-SOST-01",
213
+ "nombre": "Principio de sostenibilidad",
214
+ "severidad": "ADVERTENCIA",
215
+ "normativa": "ECM/599/2025 -> art. 3.1.k ECO/805",
216
+ "regla": "Considerar factores medioambientales y riesgos climaticos (fisicos y transicion)",
217
+ },
218
+ {
219
+ "id": "ECM-ACT-01",
220
+ "nombre": "Actualizacion plazo maximo",
221
+ "severidad": "BLOQUEANTE",
222
+ "normativa": "ECM/599/2025 -> art. 4 ECO/805",
223
+ "regla": "Actualizacion: tasacion anterior < 2 anios. Si mas -> tasacion nueva obligatoria",
224
+ "condicion": "tipo_informe == 'actualizacion'",
225
+ },
226
+ {
227
+ "id": "ECM-AUT-01",
228
+ "nombre": "Autorizacion administrativa previa",
229
+ "severidad": "BLOQUEANTE",
230
+ "normativa": "ECM/599/2025 -> art. 8.2.b ECO/805",
231
+ "regla": "Si no licencia definitiva: >= 60% PEM + conformidad urbanistica + inscripcion registral",
232
+ "condicion": "tipo_inmueble IN ['en_construccion','rehabilitacion'] AND NOT licencia_definitiva",
233
+ },
234
+ {
235
+ "id": "ECM-REG-01",
236
+ "nombre": "Certificacion registral actualizada",
237
+ "severidad": "BLOQUEANTE",
238
+ "normativa": "ECM/599/2025 -> art. 8.1.a ECO/805",
239
+ "regla": "NO fotocopias escrituras ni libro registro. Cert. registral < 3 meses fecha valoracion",
240
+ },
241
+ {
242
+ "id": "ECM-AVM-01",
243
+ "nombre": "AVM compliance",
244
+ "severidad": "ADVERTENCIA",
245
+ "normativa": "ECM/599/2025 -> nuevo art. 15 bis ECO/805",
246
+ "regla": "Si AVM: inmueble homogeneo, mercado activo, metodologia documentada. Pendiente circular BdE",
247
+ "condicion": "metodo == 'AVM'",
248
+ },
249
+ {
250
+ "id": "ECM-MINUS-01",
251
+ "nombre": "Advertencia minusvalias plazo",
252
+ "severidad": "ADVERTENCIA",
253
+ "normativa": "ECM/599/2025 -> art. 12.3 ECO/805",
254
+ "regla": "Plazo: 18 meses desde CADUCIDAD (no 1 anio desde tasacion). Sin requisito 3 anios caida",
255
+ },
256
+ {
257
+ "id": "ECM-EDIF-01",
258
+ "nombre": "Sostenibilidad en descripcion edificacion",
259
+ "severidad": "ADVERTENCIA",
260
+ "normativa": "ECM/599/2025 -> art. 71.6 ECO/805 (nuevo)",
261
+ "regla": "Incluir: calificacion energetica, consumo, emisiones CO2, renovables, aislamiento, riesgos",
262
+ },
263
+ ]
264
+
265
+ # Condicionantes (arts. 10-11) — invalidate for hipotecaria
266
+ CONDICIONANTES = [
267
+ {"id": "COND-01", "nombre": "Limitaciones documentales significativas", "art": "10.a"},
268
+ {"id": "COND-02", "nombre": "Discrepancia realidad fisica / documentacion", "art": "10.b"},
269
+ {"id": "COND-03", "nombre": "Incumplimiento urbanistico", "art": "10.c"},
270
+ {"id": "COND-04", "nombre": "Ocupacion ilegal o litigiosa", "art": "10.d"},
271
+ {"id": "COND-05", "nombre": "Cargas/servidumbres no contempladas", "art": "10.e"},
272
+ {"id": "COND-06", "nombre": "En construccion sin licencia valida", "art": "11+ECM599"},
273
+ {"id": "COND-07", "nombre": "Grado avance insuficiente", "art": "11"},
274
+ {"id": "COND-08", "nombre": "CEE ausente (CONTROVERSIA)", "art": "8+ECM599", "configurable": True},
275
+ ]
276
+
277
+ # Advertencias (arts. 12-13) — stated but don't invalidate
278
+ ADVERTENCIAS = [
279
+ {"id": "ADV-01", "nombre": "Inexistencia seguro danos", "art": "12.a"},
280
+ {"id": "ADV-02", "nombre": "Estado conservacion deficiente", "art": "12.b"},
281
+ {"id": "ADV-03", "nombre": "Antiguedad > vida util estimada", "art": "12.c"},
282
+ {"id": "ADV-04", "nombre": "Proteccion urbanistica/patrimonial", "art": "12.d"},
283
+ {"id": "ADV-05", "nombre": "Regimen proteccion publica VPO", "art": "12.e"},
284
+ {"id": "ADV-06", "nombre": "Arrendamiento vigente", "art": "12.f"},
285
+ {"id": "ADV-07", "nombre": "Sostenibilidad/riesgo climatico", "art": "3.1.k ECM599", "nuevo": True},
286
+ {"id": "ADV-MINUS", "nombre": "Posibles minusvalias futuras", "art": "13", "especial": True},
287
+ ]
288
+
289
+ # Method × property type × purpose matrix
290
+ METODOS_MATRIX = {
291
+ "vivienda_terminada": {"hipotecaria": {"obligatorio": ["comparacion"], "permitido": ["coste"]}},
292
+ "vivienda_en_construccion": {"hipotecaria": {"obligatorio": ["residual"], "permitido": ["coste"]}},
293
+ "local_comercial": {"hipotecaria": {"obligatorio": ["comparacion"], "alternativo": ["actualizacion"]}},
294
+ "oficina": {"hipotecaria": {"obligatorio": ["comparacion"], "alternativo": ["actualizacion"]}},
295
+ "nave_industrial": {"hipotecaria": {"obligatorio": ["coste"], "alternativo": ["comparacion"]}},
296
+ "solar": {"hipotecaria": {"obligatorio": ["comparacion"], "alternativo": ["residual"]}},
297
+ "finca_rustica": {"hipotecaria": {"obligatorio": ["comparacion"], "alternativo": ["actualizacion"]}},
298
+ "hotel_residencia": {"hipotecaria": {"obligatorio": ["actualizacion"], "permitido": ["coste"]}},
299
+ "edificio_completo": {"hipotecaria": {"obligatorio": ["residual"], "alternativo": ["actualizacion"]}},
300
+ }
301
+
302
+ # Quick check items (15 most common rejection causes)
303
+ QUICK_CHECK_ITEMS = [
304
+ "Firma presente en todos los documentos",
305
+ "Titulo coherente en toda la documentacion",
306
+ "CEE presente y vigente (si tasacion)",
307
+ "Comunicacion de Encargo presente",
308
+ "Referencia catastral presente y coherente",
309
+ "Nivel detalle presupuesto correcto para el tipo",
310
+ "ESS/EBSS presente y como documento separado (si aplica)",
311
+ "Estudio Geotecnico visado (si PByE)",
312
+ "Coherencia superficies memoria - planos",
313
+ "Declaracion CTE presente",
314
+ "Justificacion urbanistica presente",
315
+ "Firma electronica (si tasacion — ECM/599/2025)",
316
+ "Indice al inicio (si tasacion — ECM/599/2025)",
317
+ "Vigencia tasacion < 2 anios (si actualizacion)",
318
+ "Identificacion completa arquitecto/tasador",
319
+ ]
320
+
321
+ # College-specific requirements
322
+ COLLEGE_SPECIFICS = {
323
+ "COAC": {
324
+ "name": "Col-legi d Arquitectes de Catalunya",
325
+ "region": "Catalunya",
326
+ "additional_requirements": [
327
+ "Cedula de habitabilidad (Decreto Habitabilidad Generalitat)",
328
+ "Codi d Accessibilitat de Catalunya",
329
+ "POUM / PGM municipal aplicable",
330
+ "Documentacion valida en catalan o castellano",
331
+ "ICV 2026 ATC: comprobar valor vs coeficiente municipal (947 municipios)",
332
+ "DA 27a TRLUC: VUT licencia temporal 5 anios",
333
+ "Art. 57.3 TRLUC: reservas VPO 50%/40%",
334
+ ],
335
+ "normativa_urbanistica": "TRLUC consolidado (DLeg 1/2010 + DL 2/2025)",
336
+ "nuevo_visado": "nouvisat@coac.net (lanzamiento 27/01/2025)",
337
+ },
338
+ "COACYLE": {
339
+ "name": "Colegio de Arquitectos de Castilla y Leon",
340
+ "region": "Castilla y Leon",
341
+ "additional_requirements": [],
342
+ "normativa_urbanistica": "Ley de Urbanismo de CyL",
343
+ },
344
+ "COAM": {
345
+ "name": "Colegio de Arquitectos de Madrid",
346
+ "region": "Comunidad de Madrid",
347
+ "additional_requirements": [],
348
+ "normativa_urbanistica": "Ley del Suelo de la CAM",
349
+ },
350
+ "COAS": {
351
+ "name": "Colegio de Arquitectos de Sevilla",
352
+ "region": "Andalucia",
353
+ "additional_requirements": [
354
+ "Fichas oficiales de accesibilidad de Andalucia",
355
+ "Manual de Uso y Mantenimiento (viviendas)",
356
+ ],
357
+ "normativa_urbanistica": "LOUA",
358
+ },
359
+ }
360
+
361
+ # Comprobaciones previas obligatorias (arts. 7-9 ECO/805)
362
+ COMPROBACIONES_PREVIAS = [
363
+ {"id": "COMP-01", "nombre": "Identificacion fisica inmueble (inspeccion ocular)", "art": "7.1"},
364
+ {"id": "COMP-02", "nombre": "Estado ocupacion, uso y explotacion", "art": "7.2"},
365
+ {"id": "COMP-03", "nombre": "Adecuacion al planeamiento urbanistico", "art": "7.3"},
366
+ {"id": "COMP-04", "nombre": "Regimen de proteccion publica", "art": "7.4"},
367
+ {"id": "COMP-05", "nombre": "Adecuacion a descripcion registral", "art": "7.5"},
368
+ ]
369
+
370
+
371
+ def get_college_requirements(colegio):
372
+ if colegio and colegio.upper() in COLLEGE_SPECIFICS:
373
+ return COLLEGE_SPECIFICS[colegio.upper()]
374
+ return {"name": "CSCAE generico", "region": "Espana", "additional_requirements": [],
375
+ "normativa_urbanistica": "Legislacion autonomica aplicable"}
376
+
377
+
378
+ def get_cte_dbs(project_type):
379
+ db_map = {
380
+ "anteproyecto": {},
381
+ "proyecto_basico": {"DB-SE": "declaracion", "DB-SI": "justificacion", "DB-SUA": "declaracion",
382
+ "DB-HS": "declaracion", "DB-HR": "declaracion", "DB-HE": "declaracion"},
383
+ "proyecto_basico_ejecucion": {"DB-SE": "justificacion_detallada", "DB-SI": "justificacion_detallada",
384
+ "DB-SUA": "justificacion_detallada", "DB-HS": "justificacion_detallada",
385
+ "DB-HR": "justificacion_detallada", "DB-HE": "justificacion_detallada"},
386
+ "legalizacion": {"DB-SE": "comprobacion", "DB-SI": "comprobacion", "DB-SUA": "comprobacion",
387
+ "DB-HS": "comprobacion", "DB-HR": "comprobacion", "DB-HE": "comprobacion"},
388
+ "valoracion_eco805": {"DB-HE": "CEE_obligatorio"},
389
+ }
390
+ return db_map.get(project_type, {})
391
+
392
+
393
+ def generate_validation_config(project_type, colegio, mode):
394
+ type_config = PROJECT_TYPES.get(project_type, {})
395
+ college_config = get_college_requirements(colegio)
396
+ is_tasacion = project_type == "valoracion_eco805"
397
+
398
+ refs = [
399
+ f"references/visado/checklists/{type_config.get('checklist_file', '')}",
400
+ "references/visado/reparos/common-reparos.md",
401
+ "references/visado/normativa/cte-dbs.md",
402
+ ]
403
+ if is_tasacion:
404
+ refs.extend([
405
+ "references/visado/normativa/eco-805.md",
406
+ "references/visado/normativa/ecm-599-2025.md",
407
+ ])
408
+ if college_config.get("region") == "Catalunya":
409
+ refs.append("references/visado/coac/coac-specifics.md")
410
+
411
+ config = {
412
+ "timestamp": datetime.now().isoformat(),
413
+ "agent_version": "8.0.0",
414
+ "project_type": project_type,
415
+ "project_label": type_config.get("label", "Desconocido"),
416
+ "check_mode": mode,
417
+ "colegio": college_config["name"],
418
+ "region": college_config["region"],
419
+ "visado_obligatorio": type_config.get("visado_obligatorio", False),
420
+ "checklist_file": f"references/visado/checklists/{type_config.get('checklist_file', '')}",
421
+ "cte_justification_level": type_config.get("requires_cte_justification", False),
422
+ "requires_ref_catastral": type_config.get("requires_ref_catastral", True),
423
+ "presupuesto_level": type_config.get("presupuesto_level", "capitulos"),
424
+ "requires_comunicacion_DO": type_config.get("requires_comunicacion_DO", False),
425
+ "requires_ess": type_config.get("requires_ess", False),
426
+ "requires_geotecnico": type_config.get("requires_geotecnico", False),
427
+ "college_additional_requirements": college_config["additional_requirements"],
428
+ "normativa_urbanistica_autonomica": college_config.get("normativa_urbanistica", ""),
429
+ "references_to_load": refs,
430
+ "cte_dbs_applicable": get_cte_dbs(project_type),
431
+ }
432
+
433
+ if is_tasacion:
434
+ config["ecm599_rules"] = ECM599_RULES
435
+ config["ecm599_rules_count"] = len(ECM599_RULES)
436
+ config["condicionantes_art10_11"] = CONDICIONANTES
437
+ config["advertencias_art12_13"] = ADVERTENCIAS
438
+ config["comprobaciones_previas_art7_9"] = COMPROBACIONES_PREVIAS
439
+ config["metodos_matrix"] = METODOS_MATRIX
440
+ config["normativa_aplicada"] = "ECO/805/2003 consolidada con ECM/599/2025 (vigor 12/08/2025)"
441
+
442
+ if mode == "quick":
443
+ config["quick_check_items"] = QUICK_CHECK_ITEMS
444
+
445
+ return config
446
+
447
+
448
+ def main():
449
+ parser = argparse.ArgumentParser(description="Pre-Visa Document Validation v8")
450
+ parser.add_argument("--type", required=True, help="Project type")
451
+ parser.add_argument("--jurisdiction", default="spain")
452
+ parser.add_argument("--colegio", default="COAC")
453
+ parser.add_argument("--mode", default="full", choices=["quick", "full"])
454
+ args = parser.parse_args()
455
+
456
+ if args.type not in PROJECT_TYPES:
457
+ print(json.dumps({"valid": False, "error": f"Tipo no reconocido: {args.type}",
458
+ "valid_types": list(PROJECT_TYPES.keys())}, indent=2, ensure_ascii=False))
459
+ sys.exit(1)
460
+
461
+ config = generate_validation_config(args.type, args.colegio, args.mode)
462
+ print(json.dumps(config, indent=2, ensure_ascii=False))
463
+
464
+
465
+ if __name__ == "__main__":
466
+ main()