"""
Patch ECDIS Cartagena BOYCAR.geojson: set CATCAM from updated BOYCAR.csv.
Run once after updating the CSV with the CATCAM column.
"""
import json, csv
from pathlib import Path

GEOJSON = Path(r"D:\Proyectos Software\AR ECDIS\webecdis\data\charts\manual\BAHÍA_DE_CARTAGENA\BOYCAR.geojson")
CSV     = Path(r"D:\Proyectos Software\QGISS57Converter\capas_ctg\BOYCAR.csv")

# Load CSV catcam mapping: OBJNAM -> CATCAM int
catcam_by_name = {}
with open(CSV, newline="", encoding="utf-8-sig") as f:
    for row in csv.DictReader(f):
        name   = row.get("OBJNAM", "").strip()
        catcam = row.get("CATCAM", "").strip()
        if name and catcam:
            catcam_by_name[name] = int(catcam)

print("CSV catcam map:")
for k, v in catcam_by_name.items():
    print(f"  {k} -> {v}")


def infer_catcam(name: str) -> int:
    """Fallback inference from DIMAR naming convention."""
    n = name.upper()
    if any(x in n for x in [" SE", "(SE)", "ESTE"]):
        return 2
    if any(x in n for x in [" SO", "(SO)", " SW", "OESTE", " BB"]):
        return 4
    if any(x in n for x in [" SS", "(SS)", " VS", "SUR"]):
        return 3
    return 1  # North default


fc = json.loads(GEOJSON.read_text(encoding="utf-8"))
updated = 0
for feat in fc["features"]:
    p = feat["properties"]
    name = p.get("OBJNAM", "")
    if p.get("CATCAM") is None:
        catcam = catcam_by_name.get(name) or infer_catcam(name)
        p["CATCAM"] = catcam
        updated += 1
        print(f"  PATCHED: {name!r} -> CATCAM={catcam}")

GEOJSON.write_text(json.dumps(fc, ensure_ascii=False), encoding="utf-8")
print(f"\nDone. Updated {updated} features in {GEOJSON}")
