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19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
"""
data_normalizer.py - Smart Data Extraction + Normalization
===========================================================

Yeh module kya karta hai:
  βœ… USD β†’ INR Cr convert karta hai
  βœ… Million/Billion/Lakh β†’ Cr convert karta hai  
  βœ… Timeline ko standard format mein laata hai
  βœ… Customer, Order Type, Date accurately nikalta hai
  βœ… SEBI Annexure-A table structure samajhta hai (jo aapke PDFs mein hai)

Real-world examples jo handle karta hai:
  USD 1,346,210          β†’ 1.14 Cr  (@ Rs.85/USD)
  β‚Ή1,587.10 million      β†’ 158.71 Cr
  Rs. 890.69 Million     β†’ 89.07 Cr
  Rs. 17,750 Million     β†’ 1775.00 Cr
  INR 20.58 Crores       β†’ 20.58 Cr
  Rs. 1,827.33           β†’ 1827.33 Cr (already in Cr)
  Delivery by Oct 2027   β†’ Oct 2027
  Within 8 months        β†’ 8 Months
  910 Days               β†’ 910 Days (~30 Months)
  4 (04) Years           β†’ 4 Years (~48 Months)
  18 Months              β†’ 18 Months
"""

import re

# ─────────────────────────────────────────────────────────
# πŸ’± CURRENCY CONVERSION RATES
# Inhe update karte rahna agar rate badal jaye
# ─────────────────────────────────────────────────────────
USD_TO_INR   = 85.0    # 1 USD = Rs. 85 approx
MILLION_TO_CR = 0.1    # 1 Million = 0.1 Cr  (10 Lakh)
BILLION_TO_CR = 100.0  # 1 Billion = 100 Cr
LAKH_TO_CR    = 0.01   # 1 Lakh = 0.01 Cr
MN_TO_CR      = 0.1    # MN = Million shorthand


# ════════════════════════════════════════════════════════
# πŸ’° MAIN FUNCTION: Order Value Normalize karo
# ════════════════════════════════════════════════════════
def normalize_order_value(text: str) -> dict:
    """
    Kisi bhi format ki value ko INR Crore mein convert karta hai.
    
    Input examples:
      "USD 1,346,210"
      "β‚Ή1,587.10 million (Including GST)"
      "Rs. 890.69 Million"
      "Rs. 1,827.33 Cr"
      "INR 20.58 Crores"
      "Rs. 17,750 Million"
    
    Return:
      {
        "original": "USD 1,346,210",
        "inr_crore": 1.14,
        "inr_crore_display": "1.14 Cr",
        "currency": "USD",
        "note": "Converted @ Rs.85/USD"
      }
    """
    if not text or text.strip() in ["N/A", "", "-", "β€”"]:
        return _empty_value()
    
    clean = text.strip()
    
    # ── Pattern 1: USD amount ──
    # Matches: "USD 1,346,210" or "USD 1346210" or "US$ 1,346,210"
    usd_match = re.search(
        r"USD\s*[\$]?\s*([\d,]+(?:\.\d+)?)",
        clean, re.IGNORECASE
    )
    if usd_match:
        usd_val = float(usd_match.group(1).replace(",", ""))
        inr_val  = usd_val * USD_TO_INR
        inr_cr   = round(inr_val / 1e7, 2)  # Convert to Crore
        return {
            "original":         clean,
            "inr_crore":        inr_cr,
            "inr_crore_display": f"{inr_cr:.2f} Cr",
            "currency":         "USD",
            "note":             f"USD {usd_val:,.0f} Γ— Rs.{USD_TO_INR}/USD Γ· 1Cr"
        }
    
    # ── Pattern 2: Rupees in Million ──
    # Matches: "Rs. 890.69 Million", "β‚Ή1,587.10 million", "INR 17,750 Million", "Rs. 17,750 Mn"
    million_match = re.search(
        r"(?:Rs\.?|β‚Ή|INR|INR\s*)?\s*([\d,]+(?:\.\d+)?)\s*(?:million|mn\.?)\b",
        clean, re.IGNORECASE
    )
    if million_match:
        mn_val = float(million_match.group(1).replace(",", ""))
        cr_val = round(mn_val * MILLION_TO_CR, 2)
        return {
            "original":          clean,
            "inr_crore":         cr_val,
            "inr_crore_display": f"{cr_val:.2f} Cr",
            "currency":          "INR",
            "note":              f"Rs.{mn_val} Mn Γ· 10 = {cr_val} Cr"
        }
    
    # ── Pattern 3: Rupees in Billion ──
    # Matches: "Rs. 2.5 Billion", "INR 1 Billion"
    billion_match = re.search(
        r"(?:Rs\.?|β‚Ή|INR)?\s*([\d,]+(?:\.\d+)?)\s*(?:billion|bn\.?)\b",
        clean, re.IGNORECASE
    )
    if billion_match:
        bn_val = float(billion_match.group(1).replace(",", ""))
        cr_val = round(bn_val * BILLION_TO_CR, 2)
        return {
            "original":          clean,
            "inr_crore":         cr_val,
            "inr_crore_display": f"{cr_val:.2f} Cr",
            "currency":          "INR",
            "note":              f"Rs.{bn_val} Bn Γ— 100 = {cr_val} Cr"
        }
    
    # ── Pattern 4: Already in Crore ──
    # Matches: "Rs. 1,827.33 Cr", "INR 20.58 Crores", "Rs. 775.27 Cr. approx"
    # Also: "Rs 148 crores", "approx. Rs. 33 Crore"
    crore_match = re.search(
        r"(?:Rs\.?|β‚Ή|INR)?\s*([\d,]+(?:\.\d+)?)\s*(?:crore|cr\.?|crores)\b",
        clean, re.IGNORECASE
    )
    if crore_match:
        cr_val = round(float(crore_match.group(1).replace(",", "")), 2)
        return {
            "original":          clean,
            "inr_crore":         cr_val,
            "inr_crore_display": f"{cr_val:.2f} Cr",
            "currency":          "INR",
            "note":              "Already in Crore"
        }
    
    # ── Pattern 5: Rupees in Lakh ──
    # Matches: "Rs. 50 Lakh", "Rs. 2.5 L"
    lakh_match = re.search(
        r"(?:Rs\.?|β‚Ή|INR)?\s*([\d,]+(?:\.\d+)?)\s*(?:lakh|lac|l)\b",
        clean, re.IGNORECASE
    )
    if lakh_match:
        lakh_val = float(lakh_match.group(1).replace(",", ""))
        cr_val   = round(lakh_val * LAKH_TO_CR, 4)
        return {
            "original":          clean,
            "inr_crore":         cr_val,
            "inr_crore_display": f"{cr_val:.4f} Cr",
            "currency":          "INR",
            "note":              f"Rs.{lakh_val} L Γ· 100 = {cr_val} Cr"
        }

    # ── Fallback: Kuch match nahi hua ──
    return {
        "original":          clean,
        "inr_crore":         None,
        "inr_crore_display": clean,  # As-is rakh do
        "currency":          "UNKNOWN",
        "note":              "Auto-convert nahi hua, manual check karo"
    }


def _empty_value():
    return {
        "original": "", "inr_crore": None,
        "inr_crore_display": "N/A", "currency": "", "note": ""
    }


# ════════════════════════════════════════════════════════
# ⏰ TIMELINE NORMALIZE karo
# ════════════════════════════════════════════════════════
def normalize_timeline(text: str) -> dict:
    """
    Kisi bhi format ki timeline ko standard format mein convert karta hai.
    
    Input examples:
      "910 Days"                         β†’ {"display": "910 Days (~30 Months)", "months": 30}
      "4 (04) Years"                     β†’ {"display": "4 Years (~48 Months)",  "months": 48}
      "Within 18 Months"                 β†’ {"display": "18 Months",             "months": 18}
      "Delivery to be completed by Aug 31, 2026" β†’ {"display": "Aug 2026",      "months": None}
      "Delivery by October 2027"         β†’ {"display": "Oct 2027",              "months": None}
      "Within 8 months from LOA"         β†’ {"display": "8 Months from LOA",     "months": 8}
      "11 months from Letter of Acceptance" β†’ same pattern
    """
    if not text or text.strip() in ["N/A", "", "-"]:
        return {"display": "N/A", "months": None, "original": text}
    
    clean = text.strip()
    months = None
    display = clean  # Default: as-is

    # ── Pattern 1: Days ──
    # "910 Days", "30 days"
    days_match = re.search(r"(\d+)\s*days?\b", clean, re.IGNORECASE)
    if days_match:
        days   = int(days_match.group(1))
        months = round(days / 30.4)
        display = f"{days} Days (~{months} Months)"
        return {"display": display, "months": months, "original": clean}

    # ── Pattern 2: Years ──
    # "4 Years", "4 (04) Years", "Four (04) Years", "2.5 years"
    years_match = re.search(
        r"(\d+(?:\.\d+)?)\s*(?:\(\d+\)\s*)?years?\b",
        clean, re.IGNORECASE
    )
    if years_match:
        years  = float(years_match.group(1))
        months = round(years * 12)
        display = f"{int(years) if years == int(years) else years} Years (~{months} Months)"
        return {"display": display, "months": months, "original": clean}

    # ── Pattern 3: Months ──
    # "18 Months", "Within 18 Months", "8 months from LOA"
    months_match = re.search(r"(\d+)\s*months?\b", clean, re.IGNORECASE)
    if months_match:
        months  = int(months_match.group(1))
        # Context nikalo - "from LOA" jaisi cheez
        context_match = re.search(
            r"months?\s+(from\s+[^\.,]{3,40})", clean, re.IGNORECASE
        )
        suffix  = f" {context_match.group(1)}" if context_match else ""
        display = f"{months} Months{suffix}"
        return {"display": display, "months": months, "original": clean}

    # ── Pattern 4: Specific Date ──
    # "Delivery by October 2027", "by August 31, 2026", "by April 2026"
    date_match = re.search(
        r"(?:by|until|before|on)\s+"
        r"((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*"
        r"(?:\s+\d{1,2},?)?\s+\d{4})",
        clean, re.IGNORECASE
    )
    if date_match:
        display = date_match.group(1).strip()
        # Short month format: "October 2027" β†’ "Oct 2027"
        display = _shorten_month(display)
        return {"display": display, "months": None, "original": clean}

    # ── Fallback ──
    return {"display": clean[:60], "months": None, "original": clean}


def _shorten_month(date_str: str) -> str:
    """'October 2027' β†’ 'Oct 2027'"""
    month_map = {
        "january": "Jan", "february": "Feb", "march": "Mar",
        "april": "Apr", "may": "May", "june": "Jun",
        "july": "Jul", "august": "Aug", "september": "Sep",
        "october": "Oct", "november": "Nov", "december": "Dec"
    }
    for full, short in month_map.items():
        date_str = re.sub(full, short, date_str, flags=re.IGNORECASE)
    return date_str


# ════════════════════════════════════════════════════════
# πŸ“‹ SEBI ANNEXURE-A TABLE PARSER
# Yeh special function hai jo BSE filings ki standard table padh sakta hai
# ════════════════════════════════════════════════════════
def parse_sebi_annexure_table(text: str) -> dict:
    """
    SEBI Regulation 30 ke standard Annexure-A table se data nikalta hai.
    
    Yeh table structure handle karta hai:
      Row 1: Name of entity awarding       β†’ Customer
      Row 2: Significant terms             β†’ Order Description  
      Row 4: Nature of order               β†’ Order Type
      Row 6: Time period                   β†’ Timeline
      Row 7: Broad consideration / size    β†’ Order Value
    
    Yeh almost SABB BSE filings mein hota hai!
    """
    result = {
        "customer":          "",
        "order_description": "",
        "order_type":        "",
        "timeline_raw":      "",
        "value_raw":         "",
        "domestic_or_intl":  "",
    }
    
    if not text:
        return result

    # Normalize whitespace
    text_clean = re.sub(r"\s+", " ", text)

    # ── Row 1: Customer/Entity Name ──
    cust_patterns = [
        r"(?:name of the entity awarding[^:]*?[:]\s*)([^\n\r]{5,100}?)(?:\n|\r|$|\d+\.)",
        r"(?:entity awarding[^:]*?[:]\s*)([^\n\r]{5,100}?)(?:\n|\r|$)",
        r"(?:awarded by|awarded from)[:\s]+([A-Z][^\n\r]{5,100}?)(?:\n|\r|$)",
    ]
    for p in cust_patterns:
        m = re.search(p, text_clean, re.IGNORECASE)
        if m:
            val = m.group(1).strip()
            # Tabular "Details" header skip karo
            if len(val) > 3 and "particular" not in val.lower():
                result["customer"] = val[:120]
                break

    # ── Row 2: Order Description / Terms ──
    desc_patterns = [
        r"(?:significant terms[^:]*?[:]\s*)([^\n\r]{10,300}?)(?:\n|\r|$|\d+\.)",
        r"(?:terms and conditions[^:]*?[:]\s*)([^\n\r]{10,300}?)(?:\n|\r|$)",
    ]
    for p in desc_patterns:
        m = re.search(p, text_clean, re.IGNORECASE)
        if m:
            result["order_description"] = m.group(1).strip()[:300]
            break

    # ── Row 4: Nature of Order ──
    nature_patterns = [
        r"(?:nature of order[^:]*?[:]\s*)([^\n\r]{5,200}?)(?:\n|\r|$|\d+\.)",
    ]
    for p in nature_patterns:
        m = re.search(p, text_clean, re.IGNORECASE)
        if m:
            result["order_type"] = m.group(1).strip()[:150]
            break

    # ── Domestic/International ──
    dom_match = re.search(
        r"(?:domestic or international[^:]*?[:]\s*)([^\n\r]{3,30}?)(?:\n|\r|$|\d+\.)",
        text_clean, re.IGNORECASE
    )
    if dom_match:
        result["domestic_or_intl"] = dom_match.group(1).strip()

    # ── Row 6: Timeline ──
    time_patterns = [
        r"(?:time period[^:]*?[:]\s*)([^\n\r]{5,200}?)(?:\n|\r|$|\d+\.)",
        r"(?:period by which[^:]*?[:]\s*)([^\n\r]{5,200}?)(?:\n|\r|$)",
        r"(?:to be executed[^:]*?[:]\s*)([^\n\r]{5,200}?)(?:\n|\r|$)",
    ]
    for p in time_patterns:
        m = re.search(p, text_clean, re.IGNORECASE)
        if m:
            result["timeline_raw"] = m.group(1).strip()[:200]
            break

    # ── Row 7: Order Value ──
    value_patterns = [
        r"(?:broad consideration[^:]*?[:]\s*)([^\n\r]{5,200}?)(?:\n|\r|$|\d+\.)",
        r"(?:size of the order[^:]*?[:]\s*)([^\n\r]{5,200}?)(?:\n|\r|$)",
        r"(?:consideration or size[^:]*?[:]\s*)([^\n\r]{5,200}?)(?:\n|\r|$)",
        r"(?:value of order[^:]*?[:]\s*)([^\n\r]{5,200}?)(?:\n|\r|$)",
    ]
    for p in value_patterns:
        m = re.search(p, text_clean, re.IGNORECASE)
        if m:
            result["value_raw"] = m.group(1).strip()[:200]
            break

    return result


# ════════════════════════════════════════════════════════
# 🎯 MASTER FUNCTION - Sab ek jagah
# ════════════════════════════════════════════════════════
def extract_and_normalize(pdf_text: str, snippet: str, filing_meta: dict) -> dict:
    """
    PDF text se FULL normalized record banata hai.
    Pehle SEBI Annexure table parse karta hai (most reliable),
    phir value + timeline normalize karta hai.
    
    Return: Complete record dict for CSV
    """
    # Step 1: SEBI standard table parse karo
    annexure = parse_sebi_annexure_table(pdf_text)

    # Step 2: Value normalize karo
    raw_value = annexure["value_raw"] or snippet
    value_info = normalize_order_value(raw_value)

    # Step 3: Timeline normalize karo
    raw_timeline = annexure["timeline_raw"] or ""
    timeline_info = normalize_timeline(raw_timeline)

    # Step 4: Customer finalize
    customer = annexure["customer"]
    if not customer:
        # Fallback: snippet se try karo
        m = re.search(
            r"(?:from|by)\s+([A-Z][A-Za-z\s&\-]{5,60}"
            r"(?:Ltd\.?|Limited|Authority|Board|NHAI|DDA|NTPC|ONGC|RAIL|NAVY|ARMY))",
            snippet
        )
        if m:
            customer = m.group(1).strip()

    # Step 5: Order type finalize
    order_type = annexure["order_type"] or filing_meta.get("title", "")
    # Title se Order type nikalo agar table mein nahi mila
    if "LOA" in order_type or "Letter of Award" in (pdf_text + snippet):
        order_type = "Letter of Award"
    elif "LOI" in order_type or "Letter of Intent" in (pdf_text + snippet):
        order_type = "Letter of Intent"
    elif "Work Order" in (pdf_text + snippet):
        order_type = "Work Order"

    return {
        "Stock Name":              filing_meta.get("stock", ""),
        "Exchange":                filing_meta.get("exchange", ""),
        "Filing Title":            filing_meta.get("title", ""),
        "Customer":                customer or "N/A",
        "Order Description":       annexure["order_description"] or "N/A",
        "Order Type":              order_type or "N/A",
        "Domestic / International": annexure["domestic_or_intl"] or "N/A",
        "Date Order Received":     filing_meta.get("date", ""),

        # βœ… NORMALIZED VALUES
        "Order Value (INR Cr)":    value_info["inr_crore_display"],
        "Value (Raw)":             value_info["original"],
        "Conversion Note":         value_info["note"],

        # βœ… NORMALIZED TIMELINE
        "Timeline":                timeline_info["display"],
        "Timeline (Months)":       str(timeline_info["months"]) if timeline_info["months"] else "N/A",
        "Timeline (Raw)":          timeline_info["original"],

        "Source PDF":              filing_meta.get("pdf_url", ""),
        "Screener Date":           filing_meta.get("date", ""),
        "Scraped At":              __import__("datetime").datetime.now().strftime("%Y-%m-%d %H:%M"),
    }


# ════════════════════════════════════════════════════════
# πŸ§ͺ TEST - Seedha run karo to verify
# ════════════════════════════════════════════════════════
if __name__ == "__main__":
    print("=" * 55)
    print("πŸ’° ORDER VALUE CONVERSION TESTS")
    print("=" * 55)

    test_values = [
        "USD 1,346,210",
        "USD 1346210.00",
        "β‚Ή1,587.10 million (Including GST)",
        "Rs. 890.69 Million (including GST)",
        "Rs. 17,750 Million",
        "INR 20.58 Crores (Including Tax)",
        "Rs. 1,827.33 Cr",
        "Rs. 148 crores",
        "Rs. 775.27 Cr. approx.",
        "Rs. 33 Crore (Excl. GST)",
        "Rs. 2.13 crores (excluding taxes)",
        "Rs. 437.79 Cr. (Approx.)",
        "Rs. 1,582.11",  # Pure number - Cr assume karein
    ]

    for val in test_values:
        result = normalize_order_value(val)
        print(f"  Input : {val}")
        print(f"  Output: {result['inr_crore_display']}  [{result['note']}]")
        print()

    print("=" * 55)
    print("⏰ TIMELINE NORMALIZATION TESTS")
    print("=" * 55)

    test_timelines = [
        "910 Days",
        "Four (04) Years",
        "4 (04) Years",
        "Within 18 Months from signing of PPA",
        "Delivery to be completed by August 31, 2026",
        "Delivery by October 2027",
        "Within 8 months from the Letter of Award",
        "11 months from the date of issue of Letter of Acceptance",
        "Delivery to be completed by April 2026",
        "25 years from commissioning",
    ]

    for tl in test_timelines:
        result = normalize_timeline(tl)
        months_str = f" | {result['months']} months" if result["months"] else ""
        print(f"  Input : {tl}")
        print(f"  Output: {result['display']}{months_str}")
        print()