Spaces:
Sleeping

File size: 31,546 Bytes
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
45994d6
 
 
 
 
 
 
 
 
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d4d0bb
 
45994d6
8d4d0bb
 
 
 
 
 
 
 
 
 
 
 
3e964dd
45994d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e964dd
 
 
 
 
 
 
8d4d0bb
 
 
 
 
 
 
 
 
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
3e964dd
 
45994d6
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
3e964dd
 
 
 
45994d6
 
3e964dd
 
 
 
 
 
45994d6
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
3e964dd
8d4d0bb
45994d6
3e964dd
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
3e964dd
 
45994d6
 
8d4d0bb
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45994d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e964dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
"""Fusion node β€” assembles structured data context for the response LLM."""
from __future__ import annotations

import os

import structlog

from backend.graph.state import FiNoraState
from backend.guardrails.disclaimers import get_disclaimer

log = structlog.get_logger()

_SUMMARY_TRIGGERS = {
    "summarize", "summary", "explain", "overview", "what's happening",
    "whats happening", "tell me about", "breakdown", "analyse", "analyze",
    "give me a", "what do you think", "how is", "how's",
}


def _is_summary_query(query: str) -> bool:
    q = query.lower().strip()
    return any(trigger in q for trigger in _SUMMARY_TRIGGERS)


def _currency_sym(currency: str) -> str:
    return "β‚Ή" if currency == "INR" else "$"


def _query_period(query: str) -> tuple[str, int]:
    """
    Parse the timeframe the user is asking about.
    Returns (label, trading_days_lookback).
    trading_days_lookback == -1 β†’ use daily pct_change directly from API.
    """
    q = query.lower()
    if any(x in q for x in ("5y", "5 year", "five year")):
        return "5Y", 1250
    if any(x in q for x in ("3y", "3 year", "three year")):
        return "3Y", 750
    if any(x in q for x in ("1y", "1 year", "one year", "past year", "this year", "ytd", "annual")):
        return "1Y", 252
    if any(x in q for x in ("6m", "6 month", "six month", "half year")):
        return "6M", 126
    if any(x in q for x in ("3m", "3 month", "three month", "quarter", "quarterly")):
        return "3M", 63
    if any(x in q for x in ("1m", "month", "30 day", "past month", "this month")):
        return "1M", 21
    if any(x in q for x in ("week", "7 day", "5 day", "this week", "past week")):
        return "1W", 5
    return "1D", -1


def _period_return(rt: dict, query: str) -> tuple[str, float | None]:
    """
    Compute return for the query's timeframe from monthly bars already in realtime_context.
    monthly bars = 30 trading days β€” covers 1D / 1W / 1M accurately.
    Longer periods fall back to daily pct_change.
    """
    label, days = _query_period(query)
    if days == -1:
        return label, rt.get("pct_change")
    monthly = rt.get("monthly") or []
    closes = [b["close"] for b in monthly if b.get("close")]
    if len(closes) < 2:
        return label, rt.get("pct_change")
    last = closes[-1]
    idx = max(0, len(closes) - days)
    ref = closes[idx]
    if ref:
        return label, round((last - ref) / ref * 100, 2)
    return label, rt.get("pct_change")


def _fmt_realtime(rt: dict | None, currency: str = "USD", query: str = "") -> str:
    if not rt or not rt.get("price"):
        return "[REAL-TIME DATA UNAVAILABLE]"
    sym = _currency_sym(currency)
    ticker = rt.get("ticker", "")
    price = rt.get("price")
    change = rt.get("change")
    vol = rt.get("volume")
    avg_vol = rt.get("avg_volume_30d")
    vol_ratio = round(vol / avg_vol, 1) if vol and avg_vol else None

    period_label, period_pct = _period_return(rt, query) if query else ("1D", rt.get("pct_change"))
    daily_pct = rt.get("pct_change")

    if period_pct is not None:
        lines = [f"{ticker}: {sym}{price:.2f} ({period_pct:+.2f}% {period_label})"]
    else:
        lines = [f"{ticker}: {sym}{price:.2f}"]

    # When showing a multi-day period, also include today's daily return for context
    if period_label != "1D" and daily_pct is not None:
        lines.append(f"Today: {daily_pct:+.2f}% | {period_label} return: {period_pct:+.2f}%")

    if change and period_label == "1D":
        lines.append(f"Change: {sym}{change:+.4f}")
    if vol_ratio is not None:
        lines.append(f"Volume: {vol:,} ({vol_ratio}x 30d avg)")
    w52h = rt.get("week_52_high")
    w52l = rt.get("week_52_low")
    if w52h and w52l:
        lines.append(f"52W Range: {sym}{w52l:.2f} - {sym}{w52h:.2f}")

    return "\n".join(lines)


def _fmt_historical_patterns(patterns: list[dict]) -> str:
    """Format always-available historical patterns fetched alongside realtime data."""
    if not patterns:
        return ""
    top = patterns[:2]
    lines = [f"[HISTORICAL PATTERNS β€” {len(top)} events]"]
    for i, p in enumerate(top, 1):
        parts = [f"[{i}]"]
        if p.get("event_type"):
            parts.append(p["event_type"].replace("_", " ").title())
        if p.get("date_range"):
            parts.append(f"({p['date_range']})")
        if p.get("return_pct") is not None:
            parts.append(f"fwd return: {p['return_pct']:+.1f}%")
        if p.get("text"):
            parts.append(f"β€” {p['text'][:120]}")
        lines.append(" ".join(parts))
    return "\n".join(lines)


_CHUNK_TEXT_LIMIT = int(os.getenv("RAG_CHUNK_TEXT_LIMIT", "400"))
_MAX_NEWS_CHUNKS = int(os.getenv("RAG_MAX_NEWS_CHUNKS", "4"))
_MAX_HIST_CHUNKS = int(os.getenv("RAG_MAX_HIST_CHUNKS", "3"))


def _fmt_chunks(chunks: list[dict], label: str, max_chunks: int = _MAX_NEWS_CHUNKS) -> str:
    if not chunks:
        return f"[NO {label.upper()} DATA]"
    lines = [f"[{label.upper()} - {min(len(chunks), max_chunks)} sources]"]
    for i, ch in enumerate(chunks[:max_chunks], 1):
        source = ch.get("source", ch.get("url", "unknown"))
        date = ch.get("published_at", ch.get("start_date", ch.get("date_range", "")))
        text = ch.get("text", "")[:_CHUNK_TEXT_LIMIT]
        lines.append(f"[{i}] {source} ({date}): {text}")
    return "\n".join(lines)


def _fmt_sector_context(sc: dict | None, currency: str = "USD") -> str:
    if not sc:
        return ""
    sym = _currency_sym(currency)
    lines = []

    sector = sc.get("sector")
    etf = sc.get("sector_etf")
    if sector:
        header = f"[SECTOR CONTEXT β€” {sector}]"
        if etf:
            pct = etf.get("return_pct", 0)
            price = etf.get("price")
            etf_name = etf.get("etf", "")
            price_str = f" ({sym}{price:.2f})" if price else ""
            header += f"\nSector ETF ({etf_name}){price_str}: {pct:+.2f}% today"
        lines.append(header)

    all_etfs = sc.get("all_sector_etfs", [])
    if all_etfs:
        sorted_etfs = sorted(all_etfs, key=lambda x: x.get("return_pct", 0), reverse=True)
        etf_parts = [
            f"{e['sector']} ({e['etf']}): {e.get('return_pct', 0):+.2f}%"
            for e in sorted_etfs[:6]
        ]
        lines.append("Sector performance today:\n" + "\n".join(etf_parts))

    similar = sc.get("similar_stocks", [])
    if similar:
        sim_parts = [
            f"- {s['ticker']} ({s['exchange']}): {s['name']}"
            for s in similar[:6]
        ]
        lines.append(f"Similar stocks in {sector or 'sector'}:\n" + "\n".join(sim_parts))

    return "\n".join(lines)


def _fmt_balance_history(fd: dict | None, currency: str = "USD") -> str:
    if not fd:
        return ""
    rows: list[dict] = fd.get("annual_balance") or []
    if not rows:
        return ""
    sym = _currency_sym(currency)

    def _b(val: float | None) -> str:
        if val is None:
            return "N/A"
        return f"{sym}{val / 1e9:.1f}B"

    lines = [f"[ANNUAL BALANCE SHEET HISTORY β€” {len(rows)} fiscal years]"]
    for r in rows[:5]:
        period = r.get("period", "")
        fy = period[:4] if period else "?"
        ta = _b(r.get("total_assets"))
        tl = _b(r.get("total_liabilities"))
        eq = _b(r.get("total_equity"))
        debt = _b(r.get("long_term_debt"))
        cash = _b(r.get("cash"))
        lines.append(
            f"FY{fy} ({period}): Total Assets {ta} | Total Liabilities {tl} | "
            f"Equity {eq} | LT Debt {debt} | Cash {cash}"
        )
    return "\n".join(lines)


def _fmt_cashflow_history(fd: dict | None, currency: str = "USD") -> str:
    if not fd:
        return ""
    rows: list[dict] = fd.get("annual_cashflow") or []
    if not rows:
        return ""
    sym = _currency_sym(currency)

    def _b(val: float | None) -> str:
        if val is None:
            return "N/A"
        return f"{sym}{val / 1e9:.1f}B"

    lines = [f"[ANNUAL CASH FLOW HISTORY β€” {len(rows)} fiscal years]"]
    for r in rows[:5]:
        period = r.get("period", "")
        fy = period[:4] if period else "?"
        ocf = _b(r.get("operating_cashflow"))
        fcf = _b(r.get("free_cashflow"))
        net = _b(r.get("net_change_in_cash"))
        capex = _b(r.get("capex"))
        lines.append(
            f"FY{fy} ({period}): Operating CF {ocf} | Free CF {fcf} | "
            f"Net Change in Cash {net} | Capex {capex}"
        )
    return "\n".join(lines)


def _fmt_income_history(fd: dict | None, currency: str = "USD") -> str:
    if not fd:
        return ""
    rows: list[dict] = fd.get("annual_income") or []
    if not rows:
        return ""
    sym = _currency_sym(currency)

    def _b(val: float | None) -> str:
        if val is None:
            return "N/A"
        return f"{sym}{val / 1e9:.1f}B"

    lines = [f"[ANNUAL INCOME HISTORY β€” {len(rows)} fiscal years]"]
    for r in rows[:5]:
        period = r.get("period", "")
        fy = period[:4] if period else "?"
        rev = _b(r.get("revenue"))
        ni = _b(r.get("net_income"))
        gp = _b(r.get("gross_profit"))
        oi = _b(r.get("operating_income"))
        lines.append(
            f"FY{fy} ({period}): Revenue {rev} | Net Income {ni} | "
            f"Gross Profit {gp} | Operating Income {oi}"
        )
    return "\n".join(lines)


def _fmt_fundamentals(fd: dict | None, currency: str = "USD") -> str:
    if not fd:
        return "[FUNDAMENTAL DATA UNAVAILABLE]"
    sym = _currency_sym(currency)
    parts: list[str] = []
    if fd.get("pe"):
        parts.append(f"PE: {fd['pe']:.1f}")
    if fd.get("forward_pe"):
        parts.append(f"Forward PE: {fd['forward_pe']:.1f}")
    if fd.get("eps"):
        parts.append(f"EPS: {sym}{fd['eps']:.2f}")
    if fd.get("analyst_target"):
        parts.append(f"Analyst target: {sym}{fd['analyst_target']:.2f}")
    if fd.get("recommendation"):
        parts.append(f"Consensus: {fd['recommendation'].upper()}")
    if fd.get("profit_margins"):
        parts.append(f"Net margin: {fd['profit_margins']*100:.1f}%")
    if fd.get("beta"):
        parts.append(f"Beta: {fd['beta']:.2f}")
    if fd.get("revenue"):
        parts.append(f"Revenue: {sym}{fd['revenue']/1e9:.1f}B")
    if fd.get("market_cap"):
        mc = fd["market_cap"]
        mc_str = f"{sym}{mc/1e12:.2f}T" if mc >= 1e12 else f"{sym}{mc/1e9:.1f}B"
        parts.append(f"Mkt Cap: {mc_str}")

    consensus = fd.get("analyst_consensus") or {}
    buy = consensus.get("buy", 0) or 0
    hold = consensus.get("hold", 0) or 0
    sell = consensus.get("sell", 0) or 0
    if buy or hold or sell:
        total = buy + hold + sell
        buy_pct = round(buy / total * 100) if total else 0
        parts.append(f"Analysts: {buy} Buy / {hold} Hold / {sell} Sell ({buy_pct}% bullish)")

    return " | ".join(parts) if parts else "[LIMITED FUNDAMENTAL DATA]"

def _fmt_filings(chunks: list[dict]) -> str:
    if not chunks:
        return ""  # Silent β€” no noise for Indian stocks that have no SEC filings

    lines = [f"[FILINGS CONTEXT β€” {len(chunks)} excerpts]"]

    for i, ch in enumerate(chunks[:4], 1):
        form = ch.get("filing_type", "")
        period = ch.get("period", "")
        text = ch.get("text", "")[:400]

        lines.append(f"[{i}] {form} ({period}): {text}")

    return "\n".join(lines)


_MAX_FINANCIALS_CHUNKS = int(os.getenv("RAG_MAX_FINANCIALS_CHUNKS", "3"))


def _fmt_financials(chunks: list[dict]) -> str:
    if not chunks:
        return ""  # Silent β€” no noise for non-financial queries
    n = min(len(chunks), _MAX_FINANCIALS_CHUNKS)
    lines = [f"[FINANCIAL STATEMENTS β€” {n} periods]"]
    for i, ch in enumerate(chunks[:_MAX_FINANCIALS_CHUNKS], 1):
        period = ch.get("period_label", ch.get("period", ""))
        stmt_type = ch.get("statement_type", "")
        text = ch.get("text", "")[:500]
        lines.append(f"[{i}] {stmt_type.upper()} {period}: {text}")
    return "\n".join(lines)


def _compute_insight_flags(state: FiNoraState) -> list[str]:
    """Pre-compute interpretive signals grounded in data β€” no hallucination possible."""
    flags: list[str] = []
    rt = state.get("realtime_context") or {}
    fd = state.get("fundamental_data") or {}
    sym = _currency_sym(state.get("currency", "USD"))

    filings = state.get("filings_chunks", [])
    if filings:
        recent_forms = {ch.get("filing_type", "") for ch in filings}

        if any(f in ("10-K", "10-Q", "Annual Report", "Quarterly Results") for f in recent_forms):
            flags.append("Recent earnings/financial filings available β€” includes official performance disclosures")

        elif any(f in ("8-K", "Corporate Action") for f in recent_forms):
            flags.append("Recent corporate event filings detected β€” may indicate material business updates")

        else:
            flags.append("Recent company filings available β€” includes primary disclosures and management commentary")

    # Volume anomaly
    vol = rt.get("volume")
    avg_vol = rt.get("avg_volume_30d")
    if vol and avg_vol and avg_vol > 0:
        vol_z = vol / avg_vol
        if vol_z >= 2.5:
            flags.append(f"Volume spike: {vol_z:.1f}x 30-day average β€” unusual institutional activity likely")
        elif vol_z <= 0.4:
            flags.append("Volume well below average β€” low conviction move, may not be sustained")

    # PE interpretation
    pe = fd.get("pe")
    fpe = fd.get("forward_pe")
    if pe and pe > 0:
        if pe > 40:
            flags.append(f"PE of {pe:.1f} β€” premium valuation, priced for high earnings growth expectations")
        elif pe < 12:
            flags.append(f"PE of {pe:.1f} β€” below typical market average, may signal undervaluation or elevated risk")
        if fpe and fpe > 0:
            ratio = fpe / pe
            if ratio < 0.80:
                flags.append(
                    f"Forward PE ({fpe:.1f}) significantly below trailing ({pe:.1f}) β€” "
                    "earnings growth expected ahead"
                )
            elif ratio > 1.20:
                flags.append(
                    f"Forward PE ({fpe:.1f}) above trailing ({pe:.1f}) β€” "
                    "earnings expected to slow or decline"
                )

    # 52W range position
    price = rt.get("price")
    w52h = rt.get("week_52_high") or fd.get("week_52_high")
    w52l = rt.get("week_52_low") or fd.get("week_52_low")
    if price and w52h and w52l and w52h > w52l:
        pos_pct = ((price - w52l) / (w52h - w52l)) * 100
        if pos_pct >= 95:
            flags.append(f"Near 52-week high ({sym}{w52h:.2f}) β€” potential resistance zone")
        elif pos_pct <= 5:
            flags.append(f"Near 52-week low ({sym}{w52l:.2f}) β€” potential support zone")
        elif pos_pct >= 75:
            flags.append(f"Upper quartile of 52-week range ({pos_pct:.0f}% from low) β€” relative strength")
        elif pos_pct <= 25:
            flags.append(f"Lower quartile of 52-week range ({pos_pct:.0f}% from low) β€” relative weakness")

    # Analyst consensus
    consensus = fd.get("analyst_consensus") or {}
    buy = consensus.get("buy", 0) or 0
    hold = consensus.get("hold", 0) or 0
    sell = consensus.get("sell", 0) or 0
    total = buy + hold + sell
    if total >= 3:
        buy_pct = buy / total
        if buy_pct >= 0.75:
            flags.append(f"Strong buy consensus: {round(buy_pct*100)}% of {total} analysts rate Buy")
        elif buy_pct <= 0.25:
            flags.append(f"Weak buy consensus: only {round(buy_pct*100)}% of {total} analysts rate Buy")

    # Price vs analyst target
    target = fd.get("analyst_target") or (consensus.get("avg_target") if consensus else None)
    if price and target and target > 0:
        upside = ((target - price) / price) * 100
        if upside >= 15:
            flags.append(f"Analyst target ({sym}{target:.2f}) implies {upside:.0f}% upside from current price")
        elif upside <= -10:
            flags.append(f"Current price {abs(upside):.0f}% above consensus analyst target ({sym}{target:.2f})")

    # Profit margin
    margin = fd.get("profit_margins")
    if margin is not None:
        if margin >= 0.25:
            flags.append(f"High net margin of {margin*100:.1f}% β€” strong pricing power or operational efficiency")
        elif margin < 0.05:
            flags.append(f"Thin net margin of {margin*100:.1f}% β€” highly sensitive to cost pressures")

    # Beta
    beta = fd.get("beta")
    if beta is not None:
        if beta >= 1.5:
            flags.append(f"High beta ({beta:.2f}) β€” moves significantly more than the broader market")
        elif beta <= 0.5:
            flags.append(f"Low beta ({beta:.2f}) β€” defensive stock with low market correlation")

    return flags


def _compute_narrative_hint(state: FiNoraState) -> str:
    """Single most important signal β€” used to anchor the opening narrative sentence."""
    rt = state.get("realtime_context") or {}
    fd = state.get("fundamental_data") or {}

    pct = rt.get("pct_change")
    vol = rt.get("volume")
    avg_vol = rt.get("avg_volume_30d")
    price = rt.get("price")
    w52h = rt.get("week_52_high")
    w52l = rt.get("week_52_low")
    consensus = (fd.get("analyst_consensus") or {})
    buy = consensus.get("buy", 0) or 0
    hold = consensus.get("hold", 0) or 0
    sell = consensus.get("sell", 0) or 0
    total = buy + hold + sell

    # Priority order: large price move > volume spike > 52W extreme > consensus
    if pct is not None and abs(pct) >= 3.0:
        direction = "sharp_upward_move" if pct > 0 else "sharp_downward_move"
        return direction

    if vol and avg_vol and avg_vol > 0 and (vol / avg_vol) >= 2.5:
        return "high_volume_move"

    if price and w52h and w52l and w52h > w52l:
        pos = (price - w52l) / (w52h - w52l)
        if pos >= 0.95:
            return "near_52w_high"
        if pos <= 0.05:
            return "near_52w_low"

    if total >= 3:
        if buy / total >= 0.75:
            return "analyst_strongly_bullish"
        if buy / total <= 0.25:
            return "analyst_bearish"

    if pct is not None:
        if pct >= 1.0:
            return "mild_upward_move"
        if pct <= -1.0:
            return "mild_downward_move"

    return "consolidating"


def _compute_confidence_level(state: FiNoraState) -> str:
    """Derived confidence: how strongly do signals agree?"""
    rt = state.get("realtime_context") or {}
    fd = state.get("fundamental_data") or {}

    strong_signals = 0

    pct = rt.get("pct_change")
    if pct is not None and abs(pct) >= 2.0:
        strong_signals += 1

    vol = rt.get("volume")
    avg_vol = rt.get("avg_volume_30d")
    if vol and avg_vol and avg_vol > 0 and (vol / avg_vol) >= 2.0:
        strong_signals += 1

    price = rt.get("price")
    w52h = rt.get("week_52_high")
    w52l = rt.get("week_52_low")
    if price and w52h and w52l and w52h > w52l:
        pos = (price - w52l) / (w52h - w52l)
        if pos >= 0.85 or pos <= 0.15:
            strong_signals += 1

    consensus = (fd.get("analyst_consensus") or {})
    buy = consensus.get("buy", 0) or 0
    hold = consensus.get("hold", 0) or 0
    sell = consensus.get("sell", 0) or 0
    total = buy + hold + sell
    if total >= 3 and (buy / total >= 0.70 or buy / total <= 0.30):
        strong_signals += 1

    has_news = bool(state.get("news_chunks"))
    has_financials = bool(state.get("financials_chunks"))
    has_historical = bool(state.get("historical_chunks"))
    has_fundamentals = bool(fd)
    data_sources = sum([bool(rt), has_news, has_financials, has_historical, has_fundamentals])

    if strong_signals >= 3 and data_sources >= 3:
        return "high"
    if strong_signals >= 1 and data_sources >= 2:
        return "medium"
    return "low"


def _compute_conflict(state: FiNoraState) -> tuple[bool, str]:
    """Detect meaningful signal conflicts β€” price vs analyst, short vs long-term."""
    rt = state.get("realtime_context") or {}
    fd = state.get("fundamental_data") or {}

    pct = rt.get("pct_change")
    consensus = (fd.get("analyst_consensus") or {})
    buy = consensus.get("buy", 0) or 0
    hold = consensus.get("hold", 0) or 0
    sell = consensus.get("sell", 0) or 0
    total = buy + hold + sell

    price = rt.get("price")
    w52h = rt.get("week_52_high")
    w52l = rt.get("week_52_low")

    # Price falling but analysts strongly bullish
    if pct is not None and pct <= -2.0 and total >= 3 and buy / total >= 0.65:
        return True, "price_down_but_analyst_bullish"

    # Price rising sharply but analysts mostly bearish/hold
    if pct is not None and pct >= 2.0 and total >= 3 and (hold + sell) / total >= 0.65:
        return True, "price_up_but_analyst_cautious"

    # Near 52W low but strong buy consensus
    if price and w52h and w52l and w52h > w52l and total >= 3:
        pos = (price - w52l) / (w52h - w52l)
        if pos <= 0.15 and buy / total >= 0.65:
            return True, "near_52w_low_but_analyst_bullish"

    # Near 52W high but analyst target below current price
    target = fd.get("analyst_target") or (consensus.get("avg_target") if consensus else None)
    if price and target and w52h and w52l and w52h > w52l:
        pos = (price - w52l) / (w52h - w52l)
        if pos >= 0.85 and target < price:
            return True, "near_52w_high_but_target_below_price"

    return False, ""


def _compute_price_trend(rt: dict | None, fd: dict | None) -> dict[str, str]:
    signals: dict[str, str] = {}
    if not rt:
        return signals

    pct = rt.get("pct_change")
    if pct is not None:
        if pct >= 2.0:
            signals["short_term"] = f"Upward (+{pct:.1f}% today)"
        elif pct <= -2.0:
            signals["short_term"] = f"Downward ({pct:.1f}% today)"
        else:
            signals["short_term"] = f"Flat ({pct:+.1f}% today)"

    price = rt.get("price")
    w52h = rt.get("week_52_high")
    w52l = rt.get("week_52_low")
    if price and w52h and w52l and w52h > w52l:
        pos = (price - w52l) / (w52h - w52l)
        if pos >= 0.7:
            signals["long_term"] = "Near 52-week high β€” longer-term uptrend"
        elif pos <= 0.3:
            signals["long_term"] = "Near 52-week low β€” longer-term downtrend or consolidation"
        else:
            signals["long_term"] = "Mid-range of 52-week band"

    beta = (fd or {}).get("beta")
    if beta is not None:
        if beta >= 1.3:
            signals["volatility"] = f"High ({beta:.2f} beta) β€” amplified market moves"
        elif beta <= 0.7:
            signals["volatility"] = f"Low ({beta:.2f} beta) β€” defensive, dampened moves"
        else:
            signals["volatility"] = f"Moderate ({beta:.2f} beta)"

    return signals


def _compute_confidence(state: FiNoraState) -> float:
    score = 0.0
    if state.get("realtime_context") and state["realtime_context"].get("price"):
        score += 0.3
    if state.get("news_chunks"):
        score += 0.3
    if state.get("financials_chunks"):
        score += 0.3  # reliable for all stocks (US + Indian)
    if state.get("historical_chunks"):
        score += 0.25
    if state.get("fundamental_data"):
        score += 0.15
    if state.get("filings_chunks"):
        score += 0.1  # bonus when SEC filings available (US only)
    return min(round(score, 2), 1.0)


def _build_data_context(state: FiNoraState) -> str:
    """Pure data context β€” no behavioral instructions. Used as the user message."""
    ticker = state.get("ticker", "")
    query = state.get("query", "")
    company_name = state.get("company_name") or ticker
    currency = state.get("currency") or "USD"
    history = state.get("conversation_history", [])

    rt = state.get("realtime_context")
    fd = state.get("fundamental_data")
    insight_flags = _compute_insight_flags(state)
    trend = _compute_price_trend(rt, fd)
    narrative_hint = _compute_narrative_hint(state)
    confidence_level = _compute_confidence_level(state)
    has_conflict, conflict_reason = _compute_conflict(state)
    uncertainty_flag = confidence_level == "low" or (has_conflict and confidence_level != "high")

    rt_section = _fmt_realtime(rt, currency, query)
    news_section = _fmt_chunks(state.get("news_chunks", []), "NEWS")
    filings_section = _fmt_filings(state.get("filings_chunks", []))
    financials_section = _fmt_financials(state.get("financials_chunks", []))

    # Historical: prefer deep RAG chunks (historical_rag_node) when intent fired,
    # otherwise use always-available patterns fetched alongside realtime data
    rag_hist = state.get("historical_chunks", [])
    if rag_hist:
        hist_section = _fmt_chunks(rag_hist, "HISTORICAL PATTERN", max_chunks=_MAX_HIST_CHUNKS)
    else:
        # Always-available fallback: fetched in realtime_node concurrently
        rt_patterns = (rt or {}).get("historical_patterns", [])
        hist_section = _fmt_historical_patterns(rt_patterns)

    fund_section = _fmt_fundamentals(fd, currency)
    income_history_section = _fmt_income_history(fd, currency)
    cashflow_history_section = _fmt_cashflow_history(fd, currency)
    balance_history_section = _fmt_balance_history(fd, currency)
    sector_section = _fmt_sector_context(state.get("sector_context"), currency)

    flags_text = "\n".join(f"- {f}" for f in insight_flags[:4]) if insight_flags else "No significant flags."
    trend_text = "\n".join(
        f"- {k.replace('_', ' ').title()}: {v}" for k, v in trend.items()
    ) if trend else "Trend data unavailable."

    conv_section = ""
    if history:
        recent = history[-4:]
        conv_lines = [f"{m['role'].upper()}: {m['content'][:200]}" for m in recent]
        conv_section = "[CONVERSATION HISTORY]\n" + "\n".join(conv_lines) + "\n\n"

    # Translate internal labels β†’ natural language before sending to LLM
    # This prevents label leakage ("dominant signal suggests", "uncertainty flag")
    _HINT_TO_NL = {
        "sharp_downward_move":   "The stock is experiencing a sharp decline today.",
        "sharp_upward_move":     "The stock is surging sharply today.",
        "high_volume_move":      "Unusually high trading volume is the dominant signal today.",
        "near_52w_high":         "The stock is trading near its 52-week high.",
        "near_52w_low":          "The stock is trading near its 52-week low.",
        "analyst_strongly_bullish": "Analyst consensus is strongly bullish.",
        "analyst_bearish":       "Analyst consensus is leaning bearish.",
        "mild_upward_move":      "The stock is seeing a mild upward move today.",
        "mild_downward_move":    "The stock is seeing a mild decline today.",
        "consolidating":         "No strong directional signal is present β€” the stock is consolidating.",
    }
    market_context = _HINT_TO_NL.get(narrative_hint, "Market context is unclear.")

    _CONFIDENCE_TO_POSTURE = {
        "high":   "Be direct. State conclusions without hedging.",
        "medium": "Be measured. Use 'data shows' or 'current price action shows' β€” not 'suggests' or 'indicates'.",
        "low":    "Be cautious. Avoid directional conclusions. Acknowledge limited signal clearly.",
    }
    response_posture = _CONFIDENCE_TO_POSTURE.get(confidence_level, "Be cautious. Avoid strong conclusions.")

    if uncertainty_flag:
        response_posture += " No strong signal β€” do not construct a directional narrative."

    if has_conflict:
        _CONFLICT_NL = {
            "price_down_but_analyst_bullish":      "Price is declining but analyst consensus is bullish β€” name this divergence explicitly.",
            "price_up_but_analyst_cautious":       "Price is rising but analysts are cautious β€” name this divergence explicitly.",
            "near_52w_low_but_analyst_bullish":    "Stock is near 52-week lows but analysts rate it bullish β€” name this divergence explicitly.",
            "near_52w_high_but_target_below_price":"Stock is near 52-week highs but analyst target is below current price β€” name this divergence explicitly.",
        }
        conflict_text = _CONFLICT_NL.get(conflict_reason, f"Signal divergence detected: {conflict_reason.replace('_', ' ')}.")
    else:
        conflict_text = ""

    return f"""{conv_section}STOCK: {company_name} ({ticker}) | Currency: {currency}

[MARKET CONTEXT β€” anchor your opening sentence here]
{market_context}
{f"[SIGNAL DIVERGENCE β€” acknowledge this in your narrative]{chr(10)}{conflict_text}" if conflict_text else ""}
[RESPONSE POSTURE]
{response_posture}

[REAL-TIME DATA]
{rt_section}

[INSIGHT FLAGS]
{flags_text}

[TREND SIGNALS]
{trend_text}

[FUNDAMENTALS]
{fund_section}
{chr(10) + income_history_section if income_history_section else ""}
{chr(10) + cashflow_history_section if cashflow_history_section else ""}
{chr(10) + balance_history_section if balance_history_section else ""}
{news_section}

{financials_section if financials_section else ""}
{filings_section if filings_section else ""}

{hist_section}
{chr(10) + sector_section if sector_section else ""}"""


def fusion_node(state: FiNoraState) -> dict:
    query = state["query"]
    ticker = state.get("ticker", "")
    is_summary = _is_summary_query(query)

    data_context = _build_data_context(state)

    if is_summary:
        task = (
            "TASK: Explain what is happening with this stock right now, "
            "as if the user just opened the stock dashboard. "
            "Use the structured output format from your instructions."
        )
    else:
        task = f"QUESTION: {query}"

    fused = f"{data_context}\n\n{task}"

    confidence = _compute_confidence(state)
    disclaimer = get_disclaimer(os.getenv("DISCLAIMER_LOCALE", "IN"))

    citations: list[dict] = []
    for ch in (state.get("news_chunks") or [])[:5]:
        if ch.get("url"):
            citations.append({
                "url": ch["url"],
                "title": ch.get("title", ""),
                "source": ch.get("source", ""),
                "time": ch.get("published_at", ""),
            })

    # Filings citations β€” construct EDGAR URL from chunk metadata
    seen_accessions: set[str] = set()
    for ch in (state.get("filings_chunks") or [])[:3]:
        cik = ch.get("cik", "")
        accession = ch.get("accession", "")
        if not cik or not accession or accession in seen_accessions:
            continue
        seen_accessions.add(accession)
        filing_type = ch.get("filing_type", "Filing")
        period = ch.get("period", "")
        section_label = ch.get("section_label", "")
        ch_ticker = ch.get("ticker", ticker)
        try:
            edgar_url = (
                f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{accession}/"
            )
        except (ValueError, TypeError):
            continue
        label = section_label or filing_type
        citations.append({
            "url": edgar_url,
            "title": f"{ch_ticker} {filing_type} – {label}",
            "source": "SEC EDGAR",
            "time": period[:7] if period else "",
        })

    log.info(
        "fusion_done",
        ticker=ticker,
        mode="summary" if is_summary else "focused",
        user_mode=state.get("user_mode", "insight"),
        confidence=confidence,
        news=len(state.get("news_chunks") or []),
        historical=len(state.get("historical_chunks") or []),
    )

    return {
        "fused_context": fused,
        "confidence_score": confidence,
        "disclaimer_text": disclaimer,
        "citations": citations,
    }