#!/usr/bin/env python3 """ validate_jurisdiction.py — Detects jurisdiction and returns the applicable legal framework. Usage: python scripts/validate_jurisdiction.py --input "Madrid, Spain" [--type commercial] Output: JSON with country, currency, applicable legal references, thresholds, support tier (FULL / REFERENCE_ONLY / DETECTED_UNSUPPORTED), the calculator capabilities available for that jurisdiction, and instructions for loading the correct country reference files. Exit codes: 0 jurisdiction detected and analysis allowed (FULL or REFERENCE_ONLY) 1 jurisdiction unknown — ask the user 2 jurisdiction detected but UNSUPPORTED (no reference file) — analysis BLOCKED Coverage is declared once in data/jurisdiction_matrix.json (v14 audit F-03). Run this FIRST before any fiscal or legal analysis. """ import argparse import json import os import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MATRIX_PATH = os.path.join(ROOT, "data", "jurisdiction_matrix.json") def load_matrix() -> dict: """Load the single jurisdiction coverage matrix (fail loud if missing).""" with open(MATRIX_PATH, encoding="utf-8") as fh: return json.load(fh) # ─── Jurisdiction Framework Map ──────────────────────────────────────────────── JURISDICTION_MAP = { "spain": { "country": "spain", "country_name": "Spain / España", "currency": "EUR", "currency_symbol": "€", "stamp_duty_type": "ITP/AJD (resale) or IVA+AJD (new build)", "tax_ref": "references/countries/eu/spain/tax-law.md", "zoning_ref": "references/countries/eu/spain/zoning-law.md", "lease_ref": "references/countries/eu/spain/lease-law.md", "lease_law_primary": "LAU 2013 (Ley de Arrendamientos Urbanos) / LAE", "zoning_law_primary": "Ley del Suelo RDL 7/2015 / PGOU municipal", "financial_reporting_default": "PGC / NIIF-UE (IFRS adopted)", "high_value_threshold": 1_000_000, "high_value_currency": "EUR", "non_resident_withholding_rate": 0.03, "non_resident_withholding_note": ( "Buyer MUST withhold 3% of sale price and remit via Modelo 211 " "within 30 days of deed (IRNR Art.25.2 LIRNR). " "Buyer is jointly liable if not withheld." ), "tax_authority": "AEAT (Agencia Estatal de Administración Tributaria)", "land_registry": "Registro de la Propiedad", "analysis_label": "Analysis under Spanish law", "key_watch_points": [ "Check ITP vs IVA: resale = ITP; new build = IVA+AJD (mutually exclusive)", "Calculate Plusvalía municipal (IIVTNU) by BOTH methods (STC TC 26/2021)", "If seller is non-resident: configure 3% withholding by buyer", "Verify valor de referencia catastral vs transaction price", "Check CCAA-specific ITP rate (Madrid 6%, Cataluña 10%, Baleares 11%)", ], }, "uk": { "country": "uk", "country_name": "United Kingdom", "currency": "GBP", "currency_symbol": "£", "stamp_duty_type": "SDLT (England/NI) / LBTT (Scotland) / LTT (Wales)", "tax_ref": "references/countries/uk/tax-law.md", "zoning_ref": "references/countries/uk/zoning-law.md", "lease_ref": "references/countries/uk/lease-law.md", "lease_law_primary": "Landlord and Tenant Act 1954 / Law of Property Act 1925", "zoning_law_primary": "Town and Country Planning Act 1990 / NPPF 2023", "financial_reporting_default": "IFRS (listed) / FRS102 (SME)", "high_value_threshold": 750_000, "high_value_currency": "GBP", "non_resident_withholding_rate": None, "non_resident_withholding_note": ( "No FIRPTA-style withholding on sale. Non-resident buyer SDLT surcharge +2%. " "CGT on UK residential must be reported and paid within 60 days of completion." ), "tax_authority": "HMRC", "land_registry": "HM Land Registry", "analysis_label": "Analysis under UK law", "key_watch_points": [ "SDLT return MUST be filed within 14 days of completion (SDLT Act 2003 s.76)", "CGT on residential property: report and pay within 60 days via HMRC UK Property account", "Check if lease is inside or outside LTA 1954 (security of tenure)", "Check for ATED if company holds residential property > GBP 500K", "Check Option to Tax (OTT) status for VAT on commercial property", "Non-resident buyer SDLT surcharge: +2% on each band", ], }, "usa": { "country": "usa", "country_name": "United States of America", "currency": "USD", "currency_symbol": "$", "stamp_duty_type": "State Transfer Tax (rate varies by state; 0% Texas to 4%+ NY)", "tax_ref": "references/countries/usa/tax-law.md", "zoning_ref": "references/countries/usa/zoning-law.md", "lease_ref": "references/countries/usa/lease-law.md", "lease_law_primary": "State landlord-tenant statutes / UCC", "zoning_law_primary": "Municipal zoning ordinances / state enabling statutes", "financial_reporting_default": "US GAAP (ASC 842 leases, ASC 805 business combinations)", "high_value_threshold": 1_000_000, "high_value_currency": "USD", "non_resident_withholding_rate": 0.15, "non_resident_withholding_note": ( "FIRPTA: buyer withholds 15% of AMOUNT REALIZED (not gain) from foreign seller. " "File Form 8288 within 20 days of closing. " "Exception: price ≤ USD 300K + buyer residence use = 0%." ), "tax_authority": "IRS (federal) + State revenue departments", "land_registry": "County Recorder / Register of Deeds", "analysis_label": "Analysis under US law", "key_watch_points": [ "1031 exchange: 45-day ID window and 180-day closing window are ABSOLUTE", "Qualified Intermediary (QI) mandatory for 1031 — seller cannot touch funds", "FIRPTA: buyer withholds 15% if seller is foreign person", "Depreciation recapture (Sec.1250) taxed at max 25% — separate from LTCG rate", "State transfer tax rate varies widely — verify specific state and county", "NIIT 3.8% surtax if MAGI exceeds threshold", ], }, "france": { "country": "france", "country_name": "France", "currency": "EUR", "currency_symbol": "€", "stamp_duty_type": "Droits de mutation (~5.8%) or TVA (new build)", "tax_ref": "references/countries/eu/france/tax-law.md", "zoning_ref": "references/countries/eu/france/tax-law.md", "lease_ref": "references/countries/eu/france/tax-law.md", "lease_law_primary": "Bail commercial (Décret 1953 / Loi Pinel 2014) — 3-6-9 structure", "zoning_law_primary": "Plan Local d'Urbanisme (PLU) / Code de l'Urbanisme", "financial_reporting_default": "PCG / IFRS", "high_value_threshold": 1_000_000, "high_value_currency": "EUR", "non_resident_withholding_rate": None, "non_resident_withholding_note": ( "Non-EU residents: 26.5% CGT rate (vs 36.2% for residents). " "No withholding on purchase price." ), "tax_authority": "Direction Générale des Finances Publiques (DGFiP)", "land_registry": "Service de la publicité foncière / Cadastre", "analysis_label": "Analyse sous droit français", "key_watch_points": [ "Bail commercial: minimum 9 years; tenant can exit every 3 years with 6 months notice", "Droits de mutation ~5.8% for resale; TVA 20% for new build", "Plus-value: 36.2% total (19% + 17.2% social); exempt after 22 years (income) / 30 years (social)", "Principal residence always exempt from plus-value", "Rent indexation: ILC (shops) or ILAT (offices/logistics) — quarterly INSEE index", ], }, "germany": { "country": "germany", "country_name": "Germany / Deutschland", "currency": "EUR", "currency_symbol": "€", "stamp_duty_type": "Grunderwerbsteuer (GrESt) 3.5–6.5% depending on Bundesland", "tax_ref": "references/countries/eu/germany/tax-law.md", "zoning_ref": "references/countries/eu/germany/tax-law.md", "lease_ref": "references/countries/eu/germany/tax-law.md", "lease_law_primary": "BGB (Bürgerliches Gesetzbuch) / Gewerberaummiete", "zoning_law_primary": "BauGB / BauNVO / Bebauungsplan", "financial_reporting_default": "HGB / IFRS", "high_value_threshold": 1_000_000, "high_value_currency": "EUR", "non_resident_withholding_rate": None, "non_resident_withholding_note": ( "Same tax rules as residents. No withholding on sale price. " "Capital gains: exempt if held >10 years (individuals). " "Companies: no 10-year exemption." ), "tax_authority": "Finanzamt (local tax office)", "land_registry": "Grundbuch (Land Register)", "analysis_label": "Analyse nach deutschem Recht", "key_watch_points": [ "GrESt rate varies by Bundesland: Bavaria 3.5% (lowest) to Brandenburg/NRW/Saarland 6.5%", "Spekulationssteuer: gains on property held <10 years taxed as income (individuals)", "Share deal threshold: 90% ownership triggers GrESt (post-2021 reform)", "Grundsteuer reform 2025: new calculation method — verify current municipal rates", "Commercial rents: exempt from VAT unless landlord opts in (Optionserklärung)", ], }, "india": { "country": "india", "country_name": "India", "currency": "INR", "currency_symbol": "₹", "stamp_duty_type": "Stamp Duty (state-specific, 4–8%) + Registration fee", "tax_ref": "references/countries/india/tax-law.md", "zoning_ref": "references/countries/india/tax-law.md", "lease_ref": "references/countries/india/tax-law.md", "lease_law_primary": "Transfer of Property Act 1882 / State Rent Control Acts / RERA 2016", "zoning_law_primary": "Master Plans / Development Control Rules / RERA", "financial_reporting_default": "Ind AS / IGAAP", "high_value_threshold": 50_000_000, # 5 crore "high_value_currency": "INR", "non_resident_withholding_rate": None, "non_resident_withholding_note": ( "Sec.195 TDS: rate per applicable DTAA; without DTAA: 20%. " "FEMA: NRI/OCI can purchase residential/commercial (not agricultural). " "Repatriation subject to FEMA conditions." ), "tax_authority": "Income Tax Department / CBDT / GST Council", "land_registry": "Sub-Registrar Office (state-wise)", "analysis_label": "Analysis under Indian law", "key_watch_points": [ "Section 50C: if circle rate > sale price, capital gains computed on circle rate", "Section 56(2)(x): buyer taxed on shortfall vs circle rate if diff > ₹50K", "TDS 194-IA: buyer deducts 1% if consideration > ₹50 lakhs (Form 26QB)", "GST 5% on under-construction residential; nil on completed (post-OC)", "RERA: check registration and compliance before any developer transaction", "FEMA: verify NRI/foreign entity eligibility before acquisition", ], }, "uae": { "country": "uae", "country_name": "United Arab Emirates", "currency": "AED", "currency_symbol": "AED", "stamp_duty_type": "DLD Transfer Fee 4% (Dubai Land Department)", "tax_ref": "references/countries/uae/tax-law.md", "zoning_ref": "references/countries/uae/tax-law.md", "lease_ref": "references/countries/uae/tax-law.md", "lease_law_primary": "UAE Tenancy Law Federal / Dubai Law 26/2007 (as amended)", "zoning_law_primary": "Dubai Master Plan / Abu Dhabi Urban Planning Council", "financial_reporting_default": "IFRS", "high_value_threshold": 4_000_000, "high_value_currency": "AED", "non_resident_withholding_rate": None, "non_resident_withholding_note": ( "No capital gains tax, no income tax, no withholding on sale proceeds. " "Foreigners restricted to freehold zones only. VAT 5% on commercial leases." ), "tax_authority": "Federal Tax Authority (FTA) for VAT", "land_registry": "Dubai Land Department (DLD) / ADNOC for Abu Dhabi", "analysis_label": "Analysis under UAE law", "key_watch_points": [ "Foreign buyers: restricted to designated freehold zones only", "DLD transfer fee 4%: typically split 2% buyer / 2% seller", "Ejari registration mandatory for all tenancy contracts in Dubai", "RERA rent calculator governs permissible rent increases in Dubai", "No capital gains tax; no income tax on individuals in UAE", "VAT 5% applies to commercial lease rentals; residential exempt", ], }, "canada": { "country": "canada", "country_name": "Canada", "currency": "CAD", "currency_symbol": "C$", "stamp_duty_type": "Provincial Property Transfer Tax / Land Transfer Tax", "tax_ref": "references/countries/canada/tax-law.md", "zoning_ref": "references/countries/canada/tax-law.md", "lease_ref": "references/countries/canada/tax-law.md", "lease_law_primary": "Provincial tenancy and commercial lease law", "zoning_law_primary": "Provincial planning statutes and municipal zoning by-laws", "financial_reporting_default": "IFRS / ASPE", "high_value_threshold": 1_000_000, "high_value_currency": "CAD", "non_resident_withholding_rate": 0.25, "non_resident_withholding_note": "Section 116 compliance is transaction-specific; verify current CRA and provincial rules.", "tax_authority": "Canada Revenue Agency plus provincial authorities", "land_registry": "Provincial land registry", "analysis_label": "Analysis under applicable Canadian federal and provincial law", "key_watch_points": [ "Confirm province and municipality before quoting a rate", "Verify current foreign-buyer restrictions and provincial surcharges", "Treat the bundled reference as unverified until checked against official sources", ], }, "netherlands": { "country": "netherlands", "country_name": "Netherlands / Nederland", "currency": "EUR", "currency_symbol": "€", "stamp_duty_type": "Overdrachtsbelasting / BTW where applicable", "tax_ref": "references/countries/eu/netherlands/tax-law.md", "zoning_ref": "references/countries/eu/netherlands/tax-law.md", "lease_ref": "references/countries/eu/netherlands/tax-law.md", "lease_law_primary": "Burgerlijk Wetboek Book 7", "zoning_law_primary": "Omgevingswet and municipal omgevingsplan", "financial_reporting_default": "Dutch GAAP / IFRS", "high_value_threshold": 1_000_000, "high_value_currency": "EUR", "non_resident_withholding_rate": None, "non_resident_withholding_note": "Confirm Dutch tax residence, holding structure, and current Box 3 treatment.", "tax_authority": "Belastingdienst", "land_registry": "Kadaster", "analysis_label": "Analysis under Netherlands law", "key_watch_points": [ "Verify current transfer-tax rate and owner-occupier conditions", "Confirm municipal omgevingsplan and permit requirements", "Treat the bundled reference as unverified until checked against official sources", ], }, # Singapore: DETECTED_UNSUPPORTED (data/jurisdiction_matrix.json). No reference # file ships with the package; the detector keeps the entry so the agent can # NAME the jurisdiction and refuse, instead of mis-detecting it as another one. "singapore": { "country": "singapore", "country_name": "Singapore", "currency": "SGD", "currency_symbol": "S$", "stamp_duty_type": "BSD (Buyer's Stamp Duty) + ABSD (Additional BSD for foreigners)", "tax_ref": "references/countries/singapore/tax-law.md", "zoning_ref": "references/countries/singapore/tax-law.md", "lease_ref": "references/countries/singapore/tax-law.md", "lease_law_primary": "Conveyancing and Law of Property Act / Common law", "zoning_law_primary": "Urban Redevelopment Authority (URA) Master Plan", "financial_reporting_default": "SFRS (aligned with IFRS)", "high_value_threshold": 1_500_000, "high_value_currency": "SGD", "non_resident_withholding_rate": None, "non_resident_withholding_note": ( "ABSD: foreigners pay 60% ABSD on residential (as of 2023). " "No capital gains tax in Singapore. No withholding on sale proceeds." ), "tax_authority": "Inland Revenue Authority of Singapore (IRAS)", "land_registry": "Singapore Land Authority (SLA)", "analysis_label": "Analysis under Singapore law", "key_watch_points": [ "ABSD for foreign buyers: 60% on residential (verify current rate — changes frequently)", "BSD: 1-6% progressive on purchase price", "No capital gains tax; no withholding tax on property sale", "99-year leasehold is standard for most properties; freehold rare", "URA Master Plan governs land use — check gross plot ratio (GPR)", ], }, } # ─── Keyword Detection ──────────────────────────────────────────────────────── KEYWORDS = { "spain": [ "spain", "españa", "espana", "spanish", "madrid", "barcelona", "sevilla", "COAC", "COAM", "COACV", "COAG", "COAVN", "COACYLE", "COAS", "inversión sujeto pasivo", "ISP", "obra nueva", "AJD", "declaración obra nueva", "art.84", "art.91 LIVA", "ejecución de obra", "promotor", "IGIC", "valencia", "bilbao", "zaragoza", "malaga", "alicante", "marbella", "ITP", "AJD", "plusvalia", "IRNR", "catastro", "PGOU", "ayuntamiento", "registro propiedad", "notario", "escritura", "CCAA", "comunidad autonoma", ], "uk": [ "uk", "united kingdom", "england", "scotland", "wales", "northern ireland", "london", "manchester", "birmingham", "edinburgh", "cardiff", "glasgow", "GBP", "sterling", "pound", "SDLT", "LTA", "NPPF", "RICS", "leasehold", "freehold", "planning permission", "section 106", "land registry", "HMRC", "break clause uk", "dilapidations", "service charge", "ATED", ], "usa": [ "usa", "united states", "america", "us real estate", "california", "new york", "texas", "florida", "illinois", "massachusetts", "new jersey", "washington", "USD", "dollar", "1031", "FIRPTA", "REIT", "cap rate usa", "NNN lease", "CAM charges", "CMBS", "zoning ordinance", "HOA", "escrow usa", ], "france": [ "france", "french", "paris", "lyon", "marseille", "bordeaux", "toulouse", "nice", "nantes", "PLU", "bail commercial", "TVA immobilier", "droits de mutation", "cadastre", "notaire france", "plus-value", "DGFiP", ], "germany": [ "germany", "deutschland", "german", "berlin", "munich", "münchen", "hamburg", "frankfurt", "cologne", "köln", "düsseldorf", "stuttgart", "GrESt", "Grunderwerbsteuer", "BauGB", "Bebauungsplan", "Grundbuch", "Finanzamt", "Mietrecht", "Gewerberaum", ], "india": [ "india", "indian", "mumbai", "delhi", "bangalore", "bengaluru", "chennai", "hyderabad", "pune", "kolkata", "ahmedabad", "INR", "rupee", "crore", "lakh", "RERA", "TDS property", "stamp duty india", "GST property", "circle rate", "ready reckoner", "khata", "7/12", "CERSAI", "OC certificate india", ], "uae": [ "uae", "dubai", "abu dhabi", "sharjah", "ajman", "ras al khaimah", "AED", "dirham", "DIFC", "DLD", "freehold zone", "Ejari", "RERA dubai", "Strata Law", "ADNOC", "SPA dubai", ], "singapore": [ "singapore", "SGD", "singdollar", "URA", "HDB", "ABSD", "BSD", "master plan singapore", "plot ratio", "gross floor area singapore", "99-year leasehold", "IRAS", ], "canada": [ "canada", "canadian", "toronto", "ontario", "vancouver", "british columbia", "montreal", "quebec", "calgary", "alberta", "CAD", "CRA", "CMHC", "land transfer tax", "property transfer tax", "section 116", ], "netherlands": [ "netherlands", "nederland", "dutch", "amsterdam", "rotterdam", "utrecht", "den haag", "the hague", "kadaster", "omgevingswet", "overdrachtsbelasting", "belastingdienst", "box 3", ], } # ─── Core Functions ──────────────────────────────────────────────────────────── def detect_jurisdiction(text: str) -> dict | None: """Score each jurisdiction by keyword matches; return highest-scoring one.""" text_lower = text.lower() scores = {} for jur, kws in KEYWORDS.items(): score = sum(1 for k in kws if k.lower() in text_lower) if score > 0: scores[jur] = score if not scores: return None best = max(scores, key=scores.get) return JURISDICTION_MAP[best] def build_output(framework: dict, asset_type: str, matrix: dict | None = None) -> dict: """Build the full output object.""" matrix = matrix or load_matrix() entry = matrix["jurisdictions"].get(framework["country"], {}) tier = entry.get("tier", "DETECTED_UNSUPPORTED") reference_paths = { "tax": framework["tax_ref"], "zoning": framework["zoning_ref"], "lease": framework["lease_ref"], } missing_references = sorted({path for path in reference_paths.values() if not os.path.isfile(os.path.join(ROOT, path))}) # Analysis is allowed only when every declared reference exists AND the # matrix does not mark the jurisdiction unsupported. Both must agree. analysis_allowed = not missing_references and tier != "DETECTED_UNSUPPORTED" capabilities = { "stamp_duty_calculator": bool(entry.get("stamp_duty")), "tax_checklists": list(entry.get("tax_checklists", [])), "lease_completeness_items": bool(entry.get("lease_items")), "dscr_threshold_calibrated": bool(entry.get("dscr_calibrated")), "ltv_threshold_calibrated": bool(entry.get("ltv_calibrated")), "market_route": bool(entry.get("market_route")), "monitor_route": bool(entry.get("monitor_route")), "visado_route": bool(entry.get("visado_route")), } return { "jurisdiction_detected": framework["country"], "country_name": framework["country_name"], "currency": framework["currency"], "currency_symbol": framework["currency_symbol"], "asset_type": asset_type, "analysis_label": framework["analysis_label"], "stamp_duty_type": framework["stamp_duty_type"], "support_tier": tier, "support_tier_meaning": matrix["support_tiers"].get(tier, ""), "capabilities": capabilities, "references_to_load": reference_paths, "missing_references": missing_references, "analysis_allowed": analysis_allowed, "applicable_law": { "lease": framework["lease_law_primary"], "zoning": framework["zoning_law_primary"], "financial_reporting": framework["financial_reporting_default"], }, "thresholds": { "high_value": framework["high_value_threshold"], "high_value_currency": framework["high_value_currency"], "non_resident_withholding_rate": framework["non_resident_withholding_rate"], }, "non_resident_withholding_note": framework["non_resident_withholding_note"], "tax_authority": framework["tax_authority"], "land_registry": framework["land_registry"], "key_watch_points": framework["key_watch_points"], "instruction": ( (f"BLOCK ANALYSIS: jurisdiction '{framework['country']}' is {tier}; " f"missing {missing_references}. Tell the user this jurisdiction is recognised " "but not supported; do not quote any rate or statute. " if not analysis_allowed else "") + (f"REFERENCE_ONLY: the bundled reference is marked NO VERIFICADO and no " "calibrated calculators exist (stamp duty / tax checklist / lease items " "NOT implemented; DSCR/LTV on industry defaults). State this verbatim. " if tier == "REFERENCE_ONLY" else "") + f"Load {framework['tax_ref']} before citing any tax statute. " + f"Label all output: '{framework['analysis_label']} as of [DATE]'." ), } def supported_jurisdictions(matrix: dict | None = None) -> list[str]: """Jurisdictions on which fiscal/legal analysis may run (FULL + REFERENCE_ONLY).""" matrix = matrix or load_matrix() return [name for name, entry in matrix["jurisdictions"].items() if entry.get("tier") in {"FULL", "REFERENCE_ONLY"}] def main(): parser = argparse.ArgumentParser( description="Detect real estate jurisdiction and return applicable legal framework." ) parser.add_argument( "--input", required=True, help="Property details, address, or description (e.g. 'Office building in Madrid, Spain')", ) parser.add_argument( "--type", dest="asset_type", default="commercial", choices=["residential", "commercial", "industrial", "infrastructure", "mixed"], help="Asset type (default: commercial)", ) args = parser.parse_args() matrix = load_matrix() framework = detect_jurisdiction(args.input) if framework: result = build_output(framework, args.asset_type, matrix) print(json.dumps(result, indent=2, ensure_ascii=False)) # v16: a recognised-but-unsupported jurisdiction (e.g. Singapore) is a # loud block (exit 2), not a success with a footnote. v15 exited 0. sys.exit(0 if result["analysis_allowed"] else 2) else: error = { "error": "jurisdiction_unknown", "action": "ASK THE USER: Which country/city/state is this property located in?", "reason": ( "Cannot cite tax statutes or legal requirements without confirmed jurisdiction. " "Fiscal and legal obligations differ significantly between countries." ), "supported_jurisdictions": supported_jurisdictions(matrix), "detected_but_unsupported": [ name for name, entry in matrix["jurisdictions"].items() if entry.get("tier") == "DETECTED_UNSUPPORTED"], } print(json.dumps(error, indent=2, ensure_ascii=False)) sys.exit(1) if __name__ == "__main__": main()