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52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#!/usr/bin/env python3
"""
Parse Raw Programme — Transform pasted surgery lists into structured cases

Accepts raw text (the messy hand-written programme) and produces structured
case dicts compatible with PROGRAM_CASES format / BlocCase creation.

Usage:
    # As a module
    from scripts.surgery.parse_programme import parse_raw_programme
    cases = parse_raw_programme(raw_text)

    # CLI
    PYTHONPATH=src python3 scripts/surgery/parse_programme.py < programme.txt
    PYTHONPATH=src python3 scripts/surgery/parse_programme.py --file programme.txt

Design:
    - Regex-based line parser
    - Category detection from section headers
    - ASA normalization (ASA1/Asa1/ASAI/ASA I → ASA_I)
    - Phone extraction and normalization
    - Free-text note extraction (blockers, logistics, evidence)
    - Preserves raw source text for audit
"""

from __future__ import annotations

import re
import json
import sys
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple


# ═══════════════════════════════════════════════════════════
# CATEGORY DETECTION — from section headers
# ═══════════════════════════════════════════════════════════

SECTION_PATTERNS: List[Tuple[re.Pattern, str, str]] = [
    (re.compile(r"(?:^|\n)\s*#{1,4}\s*VBL", re.IGNORECASE), "vbl", "simple_vbl"),
    (re.compile(r"(?:^|\n)\s*#{1,4}\s*(?:Hernies?\s+ombilicale|hernie.*ombili)", re.IGNORECASE), "hernia", "umbilical_hernia"),
    (re.compile(r"(?:^|\n)\s*#{1,4}\s*(?:Hernie.*inguino\s*scrotale)", re.IGNORECASE), "hernia", "inguinoscrotal_hernia"),
    (re.compile(r"(?:^|\n)\s*#{1,4}\s*(?:Hernie.*inguinale)", re.IGNORECASE), "hernia", "inguinal_hernia"),
    (re.compile(r"(?:^|\n)\s*#{1,4}\s*Eventration", re.IGNORECASE), "hernia", "eventration"),
    (re.compile(r"(?:^|\n)\s*#{1,4}\s*Lipome", re.IGNORECASE), "wall_soft_tissue", "lipoma"),
    (re.compile(r"(?:^|\n)\s*#{1,4}\s*Paroi", re.IGNORECASE), "wall_soft_tissue", "parietal_hematoma"),
    (re.compile(r"(?:^|\n)\s*#{1,4}\s*Kyste", re.IGNORECASE), "wall_soft_tissue", "cyst"),
    (re.compile(r"(?:^|\n)\s*#{1,4}\s*UNKNOWN", re.IGNORECASE), "other", "other"),
]


# ═══════════════════════════════════════════════════════════
# ASA NORMALIZATION
# ═══════════════════════════════════════════════════════════

ASA_PATTERNS = [
    (re.compile(r"\bASA\s*(?:II|2)\b", re.IGNORECASE), 2),
    (re.compile(r"\bASA\s*(?:III|3)\b", re.IGNORECASE), 3),
    (re.compile(r"\bASA\s*(?:IV|4)\b", re.IGNORECASE), 4),
    (re.compile(r"\bASA\s*(?:V|5)\b", re.IGNORECASE), 5),
    (re.compile(r"\bASA\s*(?:I|1)\b", re.IGNORECASE), 1),
    (re.compile(r"\bAs[a]?\s*1\b", re.IGNORECASE), 1),
    (re.compile(r"\bAs[a]?\s*2\b", re.IGNORECASE), 2),
]


def normalize_asa(text: str) -> Optional[int]:
    """Extract and normalize ASA score from text."""
    for pattern, score in ASA_PATTERNS:
        if pattern.search(text):
            return score
    return None


# ═══════════════════════════════════════════════════════════
# PHONE NORMALIZATION
# ═══════════════════════════════════════════════════════════

PHONE_RE = re.compile(r"(?:0\d[\s.]?\d{2}[\s.]?\d{2}[\s.]?\d{2}[\s.]?\d{2})")


def normalize_phone(text: str) -> Optional[str]:
    """Extract and normalize phone number (Moroccan format)."""
    match = PHONE_RE.search(text)
    if match:
        return re.sub(r"[\s.]", "", match.group())
    return None


# ═══════════════════════════════════════════════════════════
# DIAGNOSIS NORMALIZATION
# ═══════════════════════════════════════════════════════════

DIAGNOSIS_MAP: List[Tuple[re.Pattern, str, str]] = [
    (re.compile(r"cholecystite", re.IGNORECASE), "Cholécystite aiguë", "cholecystitis"),
    (re.compile(r"vblsa.*pancr|pancr.*vblsa", re.IGNORECASE), "VBLSA + antécédent de pancréatite biliaire", "vbl_pancreatitis_history"),
    (re.compile(r"vblsa", re.IGNORECASE), "VBLSA (VBL symptomatique avec antécédent)", "simple_vbl"),
    (re.compile(r"vbls(?!a)", re.IGNORECASE), "VBLS (VBL symptomatique)", "simple_vbl"),
    (re.compile(r"\bvbl\b", re.IGNORECASE), "VBL (lithiase vésiculaire)", "simple_vbl"),
    (re.compile(r"hernie\s+inguino\s*scrotale", re.IGNORECASE), "Hernie inguinoscrotale", "inguinoscrotal_hernia"),
    (re.compile(r"hernie\s+sus[\s-]?ombilicale", re.IGNORECASE), "Hernie sus-ombilicale", "supra_umbilical_hernia"),
    (re.compile(r"hernie\s+ombilicale", re.IGNORECASE), "Hernie ombilicale", "umbilical_hernia"),
    (re.compile(r"hernie\s+inguinale|HIG", re.IGNORECASE), "Hernie inguinale", "inguinal_hernia"),
    (re.compile(r"\bhernie\b", re.IGNORECASE), "Hernie (type à préciser)", "other"),
    (re.compile(r"lipome", re.IGNORECASE), "Lipome", "lipoma"),
    (re.compile(r"hematome\s+parietal|parietal.*hematome", re.IGNORECASE), "Hématome pariétal", "parietal_hematoma"),
    (re.compile(r"kyste\s+perin", re.IGNORECASE), "Kyste périnéal", "perineal_cyst"),
    (re.compile(r"kyste.*cuir\s+chevel|kyste\s+seb", re.IGNORECASE), "Kyste sébacé cuir chevelu", "scalp_cyst"),
    (re.compile(r"kyste", re.IGNORECASE), "Kyste", "cyst"),
    (re.compile(r"eventration", re.IGNORECASE), "Éventration", "eventration"),
]


def normalize_diagnosis(text: str, section_procedure: str) -> Tuple[str, str]:
    """Normalize diagnosis from free text. Returns (diagnosis_label, procedure_type)."""
    for pattern, label, proc in DIAGNOSIS_MAP:
        if pattern.search(text):
            return label, proc
    return f"À préciser ({text[:60]})", section_procedure


# ═══════════════════════════════════════════════════════════
# FREE-TEXT NOTE EXTRACTION
# ═══════════════════════════════════════════════════════════

BLOCKER_PATTERNS = [
    (re.compile(r"bilan\s+non\s+delivree?", re.IGNORECASE), "missing_workup", "Bilan non délivrée"),
    (re.compile(r"(?:TP|tp)\s*(\d+)%", re.IGNORECASE), "abnormal_biology", None),
    (re.compile(r"non\s+joignable", re.IGNORECASE), "contact_unreachable", "Non joignable"),
    (re.compile(r"prisonn?ier", re.IGNORECASE), "prisoner", "Prisonnier"),
    (re.compile(r"avis\s+uro", re.IGNORECASE), "external_opinion", "Avis urologique requis"),
    (re.compile(r"alitante", re.IGNORECASE), "mobility_issue", "Patiente alitante"),
    (re.compile(r"voyage", re.IGNORECASE), "travel_constraint", "Patiente en voyage"),
]

EVIDENCE_PATTERNS = [
    (re.compile(r"bilan\s+ok|bilan\s+delivree?", re.IGNORECASE), "lab", "ok"),
    (re.compile(r"\bCPA\b", re.IGNORECASE), "anesthesia", "ok"),
    (re.compile(r"bili[\s-]?irm", re.IGNORECASE), "mri", "pending"),
    (re.compile(r"-bilan|-rxthorax|bilan.*manqu", re.IGNORECASE), "lab", "missing"),
    (re.compile(r"\btp\s+tck\b", re.IGNORECASE), "lab", "pending"),
]

STATUS_PATTERNS = [
    (re.compile(r"operer\s+ext|operer$|chirurgie\s+ext", re.IGNORECASE), "external_management"),
    (re.compile(r"spasfon", re.IGNORECASE), "current_treatment"),
]


def extract_notes(text: str) -> Dict[str, Any]:
    """Extract structured info from free-text notes."""
    result: Dict[str, Any] = {
        "blockers": [],
        "evidence_hints": [],
        "logistics_flags": [],
        "biology_status": "missing",
        "imaging_status": "missing",
        "anesthesia_clearance": "missing",
        "contact_status": "joignable",
        "logistic_constraints": None,
    }

    for pattern, blocker_type, label in BLOCKER_PATTERNS:
        m = pattern.search(text)
        if m:
            if blocker_type == "abnormal_biology":
                tp_val = m.group(1) if m.lastindex else ""
                result["blockers"].append(f"TP {tp_val}% — coagulation anormale")
                result["biology_status"] = "abnormal"
            elif blocker_type == "contact_unreachable":
                result["contact_status"] = "non_joignable"
                result["blockers"].append(label)
            elif blocker_type == "prisoner":
                result["logistics_flags"].append("prisoner")
                result["contact_status"] = "prisonnier"
            elif blocker_type == "mobility_issue":
                result["logistics_flags"].append("mobility")
                result["logistic_constraints"] = label
            elif blocker_type == "travel_constraint":
                result["logistics_flags"].append("travel")
                result["logistic_constraints"] = label
            elif blocker_type == "external_opinion":
                result["logistics_flags"].append("external_opinion")
                result["blockers"].append(label)
            elif blocker_type == "missing_workup":
                result["blockers"].append(label)
                result["biology_status"] = "missing"

    for pattern, ev_type, status in EVIDENCE_PATTERNS:
        if pattern.search(text):
            result["evidence_hints"].append({"type": ev_type, "status": status})
            if ev_type == "lab" and status == "ok":
                result["biology_status"] = "ok"
            elif ev_type == "lab" and status == "missing":
                result["biology_status"] = "missing"
            elif ev_type == "anesthesia" and status == "ok":
                result["anesthesia_clearance"] = "ok"
            elif ev_type == "mri" and status == "pending":
                result["imaging_status"] = "pending"

    return result


# ═══════════════════════════════════════════════════════════
# DATE EXTRACTION
# ═══════════════════════════════════════════════════════════

DATE_RE = re.compile(r"(\d{2})/(\d{2})/(\d{4})")


def extract_date(text: str) -> Optional[str]:
    """Extract date in dd/mm/yyyy format and return as ISO string."""
    m = DATE_RE.search(text)
    if m:
        day, month, year = m.groups()
        return f"{year}-{month}-{day}"
    return None


# ═══════════════════════════════════════════════════════════
# CLASSIFY CASE — operational grouping
# ═══════════════════════════════════════════════════════════

def classify_case(case: Dict[str, Any]) -> Tuple[str, str, str]:
    """
    Determine operational_group, decision, and next_action.

    Returns (operational_group, decision, next_action)
    """
    bio = case.get("biology_status", "missing")
    img = case.get("imaging_status", "missing")
    anes = case.get("anesthesia_clearance", "missing")
    blockers = case.get("blockers", [])
    logistics = case.get("logistics_flags", [])
    certainty = case.get("certainty_level", "uncertain")
    contact = case.get("contact_status", "joignable")

    # External management
    if any(re.search(r"operer\s+ext|chirurgie\s+ext", b, re.IGNORECASE) for b in blockers):
        return "external", "completed", "mark_external_management"

    # Logistics special
    if "prisoner" in logistics:
        return "logistics_special", "operate", "resolve_logistics"
    if contact == "non_joignable":
        return "logistics_special", "operate", "follow_up_contact"
    if any(f in logistics for f in ("mobility", "travel")):
        return "logistics_special", "operate", "resolve_logistics"

    # All ready
    if bio == "ok" and anes == "ok" and img in ("ok", "na") and certainty in ("certain", "probable"):
        return "ready_for_bloc", "operate", "send_to_bloc"

    # Abnormal biology → optimize
    if bio == "abnormal":
        return "optimize_before_bloc", "optimize", "correct_biology"

    # External opinion pending
    if "external_opinion" in logistics:
        return "optimize_before_bloc", "optimize", "obtain_external_opinion"

    # Missing evidence
    if bio == "missing" or img == "missing" or anes == "missing":
        return "awaiting_evidence", "observe", "complete_workup"

    # Pending imaging
    if img == "pending":
        return "awaiting_evidence", "observe", "request_imaging"

    # Uncertain diagnosis
    if certainty == "uncertain":
        return "needs_review", "observe", "review_case"

    return "needs_review", "observe", "review_case"


# ═══════════════════════════════════════════════════════════
# MAIN PARSER
# ═══════════════════════════════════════════════════════════

def parse_raw_programme(
    raw_text: str,
    batch_id: Optional[str] = None,
) -> List[Dict[str, Any]]:
    """
    Parse raw pasted programme text into structured case dicts.

    Each line starting with * is treated as a case entry.
    Section headers (#### VBL, #### Hernies, etc.) set the current category.

    Returns list of case dicts compatible with BlocCase creation.
    """
    if batch_id is None:
        batch_id = f"import_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"

    cases: List[Dict[str, Any]] = []
    current_category = "other"
    current_procedure = "other"

    for line in raw_text.splitlines():
        stripped = line.strip()
        if not stripped:
            continue

        # Check for section headers
        for pattern, cat, proc in SECTION_PATTERNS:
            if pattern.search(stripped):
                current_category = cat
                current_procedure = proc
                break

        # Case lines start with * or -
        if not stripped.startswith(("*", "-")):
            continue

        # Remove leading * or - and whitespace
        case_text = stripped.lstrip("*- ").strip()
        if not case_text:
            continue

        # Split on em-dash (—) or double-dash (--)
        parts = re.split(r"\s*[—–]\s*|\s+--\s+", case_text)
        parts = [p.strip() for p in parts if p.strip()]

        if not parts:
            continue

        # First part is always the name
        patient_name = parts[0]

        # Rejoin all parts for full-text analysis
        full_text = " ".join(parts)

        # Extract structured fields
        asa = normalize_asa(full_text)
        phone = normalize_phone(full_text)
        sched_date = extract_date(full_text)
        diagnosis, procedure_type = normalize_diagnosis(full_text, current_procedure)
        notes = extract_notes(full_text)

        # If name looks like a phone number, skip
        if re.match(r"^0\d{9}$", patient_name):
            continue

        # Determine certainty
        certainty = "uncertain"
        if notes["biology_status"] == "ok" and notes["anesthesia_clearance"] == "ok":
            certainty = "certain"
        elif notes["biology_status"] == "ok" or notes["anesthesia_clearance"] == "ok":
            certainty = "probable"

        case: Dict[str, Any] = {
            "patient_name": patient_name,
            "phone": phone,
            "diagnosis": diagnosis,
            "program_category": current_category,
            "procedure_type": procedure_type,
            "certainty_level": certainty,
            "asa_score": asa,
            "urgency": "elective",
            "risk_level": "low",
            "biology_status": notes["biology_status"],
            "imaging_status": notes["imaging_status"],
            "anesthesia_clearance": notes["anesthesia_clearance"],
            "consent_status": "missing",
            "contact_status": notes["contact_status"],
            "logistic_constraints": notes.get("logistic_constraints"),
            "logistics_flag": notes["logistics_flags"][0] if notes["logistics_flags"] else "none",
            # Import tracking
            "source_program": "programme_chirurgie",
            "raw_source_text": case_text,
            "import_batch_id": batch_id,
            "created_from_import": True,
            "review_required": True,  # All parsed cases need review
        }

        if sched_date:
            case["scheduled_date"] = sched_date

        # Build evidence list from hints
        evidence = []
        for hint in notes["evidence_hints"]:
            evidence.append({
                "evidence_type": hint["type"],
                "summary": f"Extrait automatiquement du texte brut",
                "is_conclusive": hint["status"] == "ok",
            })
        case["evidence"] = evidence

        # Classify
        group, decision, next_action = classify_case({**case, **notes})
        case["operational_group"] = group
        case["decision"] = decision
        case["next_action"] = next_action

        cases.append(case)

    return cases


def print_parsed_cases(cases: List[Dict[str, Any]]):
    """Print parsed cases in a readable format."""
    print(f"\n{'=' * 70}")
    print(f"  PARSED PROGRAMME — {len(cases)} cases")
    print(f"{'=' * 70}")

    groups: Dict[str, List[Dict]] = {}
    for c in cases:
        g = c.get("operational_group", "needs_review")
        groups.setdefault(g, []).append(c)

    for group, group_cases in sorted(groups.items()):
        print(f"\n  [{group.upper()}] — {len(group_cases)} cases")
        for c in group_cases:
            asa = f"ASA {c['asa_score']}" if c.get("asa_score") else "ASA ?"
            phone = c.get("phone", "—")
            decision = c.get("decision", "?")
            next_act = c.get("next_action", "?")
            print(f"    • {c['patient_name']:<25} {asa:<8} ☎ {phone:<15} → {decision} → {next_act}")
            if c.get("logistic_constraints"):
                print(f"      ⚠ {c['logistic_constraints']}")


# ═══════════════════════════════════════════════════════════
# CLI
# ═══════════════════════════════════════════════════════════

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Parse raw surgery programme text")
    parser.add_argument("--file", "-f", help="Input file (default: stdin)")
    parser.add_argument("--json", action="store_true", help="Output as JSON")
    parser.add_argument("--batch-id", help="Import batch ID")
    args = parser.parse_args()

    if args.file:
        with open(args.file, "r", encoding="utf-8") as f:
            raw = f.read()
    else:
        raw = sys.stdin.read()

    cases = parse_raw_programme(raw, batch_id=args.batch_id)

    if args.json:
        print(json.dumps(cases, indent=2, ensure_ascii=False, default=str))
    else:
        print_parsed_cases(cases)