File size: 16,855 Bytes
4067247
 
 
 
 
 
8a28a5a
4067247
8a28a5a
 
 
 
4067247
 
 
 
544a240
8a28a5a
4067247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8788448
 
4067247
8a28a5a
 
 
4067247
8a28a5a
544a240
 
8a28a5a
4067247
245be96
 
 
 
 
 
 
4067247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245be96
 
 
 
 
 
 
4067247
 
 
 
 
 
 
 
 
 
245be96
 
 
4067247
245be96
4067247
 
 
245be96
4067247
 
 
 
 
 
245be96
 
 
 
 
 
 
 
 
 
 
4067247
 
 
 
 
 
 
 
 
 
 
 
245be96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4067247
245be96
 
 
 
 
 
4067247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245be96
 
4067247
245be96
4067247
 
 
 
 
 
 
 
 
8a28a5a
4067247
 
 
 
8a28a5a
4067247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a28a5a
4067247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a28a5a
4067247
 
 
 
 
 
 
 
 
 
245be96
 
 
 
 
 
 
 
4067247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
544a240
8a28a5a
 
 
544a240
8a28a5a
4067247
8a28a5a
6b85e2b
8a28a5a
4067247
8a28a5a
 
544a240
4067247
 
 
 
 
 
 
 
544a240
 
 
4067247
544a240
 
 
 
 
4067247
 
 
544a240
8a28a5a
 
 
4067247
 
 
245be96
4067247
 
 
 
 
 
 
8a28a5a
245be96
 
4067247
245be96
 
 
4067247
245be96
4067247
245be96
 
 
4067247
8a28a5a
4067247
 
 
 
544a240
b3db377
4067247
 
b3db377
4067247
 
 
 
 
 
 
 
 
b3db377
4067247
 
 
b3db377
 
 
 
4067247
 
 
 
 
 
 
 
 
 
 
 
 
b3db377
4067247
b3db377
4067247
 
 
 
 
 
 
 
b3db377
4067247
 
 
 
 
245be96
 
 
 
 
 
 
 
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
import os
import json
import random
import re
from datetime import datetime, timedelta, timezone

import streamlit as st
import streamlit.components.v1 as components
import google.generativeai as genai
from supabase import create_client
import trafilatura


# =========================================================
# CONFIGURAZIONE APP
# =========================================================
st.set_page_config(page_title="Elite Finance Summit", layout="wide")


# =========================================================
# COSTANTI
# =========================================================
EXPERTS = [
    "Warren Buffett",
    "Ray Dalio",
    "Ed Yardeni",
    "Nassim Taleb",
    "Nouriel Roubini",
    "Cathie Wood",
    "Mohamed El-Erian",
    "Howard Marks",
    "Jerome Powell",
    "Paul Krugman",
    "Peter Schiff",
    "Janet Yellen",
    "Thomas Piketty",
    "Larry Fink",
    "Christine Lagarde",
]

VALID_MOODS = {"Bullish", "Bearish"}


# =========================================================
# INIZIALIZZAZIONE SERVIZI
# =========================================================
supabase = None
model = None

try:
    genai.configure(api_key=os.environ["GEMINI_API_KEY"])
    supabase = create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"])
    model = genai.GenerativeModel("gemini-2.5-flash")
except Exception as e:
    st.error(f"🚨 Errore di connessione ai Secrets: {e}")
    st.stop()


# =========================================================
# SESSION STATE
# =========================================================
if "visible_posts" not in st.session_state:
    st.session_state.visible_posts = 10


# =========================================================
# UTILS GENERALI
# =========================================================
def now_utc():
    return datetime.now(timezone.utc)


def safe_str(value, default=""):
    return value if isinstance(value, str) else default


def normalize_reply_to(value):
    if value is None:
        return None
    value = str(value).strip()
    if value.lower() in {"null", "none", ""}:
        return None
    return value


def extract_json_object(raw_text: str) -> dict:
    """
    Estrae il primo oggetto JSON valido dal testo del modello.
    Gestisce sia blocchi ```json ... ``` sia testo sporco intorno.
    """
    if not raw_text or not isinstance(raw_text, str):
        raise ValueError("Risposta vuota dal modello")

    cleaned = raw_text.strip()
    cleaned = cleaned.replace("```json", "").replace("```", "").strip()

    try:
        return json.loads(cleaned)
    except json.JSONDecodeError:
        pass

    match = re.search(r"\{.*\}", cleaned, re.DOTALL)
    if match:
        candidate = match.group(0)
        return json.loads(candidate)

    raise ValueError("Nessun JSON valido trovato nella risposta del modello")


def validate_model_output(data: dict) -> dict:
    """
    Validazione forte dell'output del modello.
    Controlla:
    - struttura JSON
    - esattamente 15 commenti
    - un solo commento per esperto
    - primi 3 root
    - i successivi 12 devono essere reply validi
    """
    if not isinstance(data, dict):
        raise ValueError("L'output del modello non è un oggetto JSON")

    ticker = safe_str(data.get("ticker"), "NONE").strip() or "NONE"
    comments = data.get("commenti")

    if not isinstance(comments, list):
        raise ValueError("Il campo 'commenti' non è una lista")

    if len(comments) != 15:
        raise ValueError(f"Il modello deve restituire esattamente 15 commenti, non {len(comments)}")

    validated_comments = []
    used_users = set()

    for idx, c in enumerate(comments):
        if not isinstance(c, dict):
            raise ValueError(f"Commento {idx + 1} non valido")

        user = safe_str(c.get("user")).strip()
        mood = safe_str(c.get("mood")).strip()
        text = safe_str(c.get("text")).strip()
        reply_to = normalize_reply_to(c.get("reply_to"))

        if not user:
            raise ValueError(f"Commento {idx + 1}: user mancante")

        if user not in EXPERTS:
            raise ValueError(f"Commento {idx + 1}: user non ammesso ({user})")

        if user in used_users:
            raise ValueError(f"Commento {idx + 1}: esperto duplicato ({user})")

        if not text:
            raise ValueError(f"Commento {idx + 1}: testo vuoto")

        if mood not in VALID_MOODS:
            mood = "Bearish"

        text = re.sub(r"\s+", " ", text).strip()

        validated_comments.append({
            "user": user,
            "mood": mood,
            "text": text,
            "reply_to": reply_to
        })
        used_users.add(user)

    for i in range(3):
        if validated_comments[i]["reply_to"] is not None:
            raise ValueError(f"Il commento {i + 1} deve avere reply_to = null")

    seen_users = {
        validated_comments[0]["user"],
        validated_comments[1]["user"],
        validated_comments[2]["user"],
    }

    for i in range(3, 15):
        reply_to = validated_comments[i]["reply_to"]

        if reply_to is None:
            raise ValueError(f"Il commento {i + 1} deve essere una risposta, non un root")

        if reply_to not in seen_users:
            raise ValueError(
                f"Il commento {i + 1} risponde a '{reply_to}', ma quel nome non è ancora apparso prima"
            )

        seen_users.add(validated_comments[i]["user"])

    return {
        "ticker": ticker,
        "commenti": validated_comments
    }


def format_created_at(value: str) -> str:
    if not value:
        return "-"
    try:
        dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
        return dt.strftime("%d/%m/%Y %H:%M")
    except Exception:
        return value[:16]


# =========================================================
# WIDGET TRADINGVIEW
# =========================================================
def mostra_grafico(ticker: str, chart_id: str):
    if not ticker or ticker == "NONE":
        return

    html = f"""
    <div style="height:400px;">
        <script src="https://s3.tradingview.com/tv.js"></script>
        <div id="{chart_id}"></div>
        <script>
            new TradingView.widget({{
                "width": "100%",
                "height": 400,
                "symbol": "{ticker}",
                "interval": "D",
                "theme": "dark",
                "container_id": "{chart_id}"
            }});
        </script>
    </div>
    """
    components.html(html, height=410)


# =========================================================
# ESTRAZIONE TESTO DA URL
# =========================================================
def prepara_testo_da_analizzare(input_news: str) -> str:
    testo = input_news.strip()

    if not testo.startswith("http"):
        return testo

    try:
        downloaded = trafilatura.fetch_url(testo)
        if not downloaded:
            return testo

        extracted = trafilatura.extract(downloaded)
        if extracted:
            return f"Articolo estratto:\n\n{extracted}"

        return testo
    except Exception:
        return testo


# =========================================================
# GEMINI
# =========================================================
def build_prompt(testo_completo: str) -> str:
    expert_list = ", ".join(EXPERTS)

    return f"""
ANALIZZA QUESTO CONTENUTO:
{testo_completo}

TASK:
Genera un acceso dibattito in ITALIANO tra questi 15 esperti viventi:
{expert_list}

REGOLE OBBLIGATORIE:
- Esattamente 15 commenti totali.
- Ogni commento deve essere tra 50 e 80 parole.
- I primi 3 commenti devono lanciare il tema e avere "reply_to": null.
- Gli altri 12 devono rispondere ai primi o ad altri commenti precedenti, criticando o concordando in modo tecnico.
- Se è una risposta, il campo "reply_to" deve contenere il nome esatto di uno degli esperti già comparsi prima.
- Il campo "user" deve essere uno e uno solo tra i 15 nomi indicati.
- Ogni esperto deve comparire una sola volta.
- Il campo "mood" deve essere solo "Bullish" oppure "Bearish".
- Il campo "ticker" deve essere un simbolo finanziario plausibile oppure "NONE".

RESTITUISCI SOLO JSON PURO, senza testo introduttivo, senza markdown, senza commenti.

Formato richiesto:
{{
  "ticker": "SIMBOLO_FINANZIARIO_O_NONE",
  "commenti": [
    {{
      "user": "Nome Cognome",
      "mood": "Bullish",
      "text": "testo commento",
      "reply_to": null
    }}
  ]
}}
"""


def genera_summit(testo_completo: str, post_id: str):
    prompt = build_prompt(testo_completo)

    try:
        response = model.generate_content(prompt)
        raw_text = safe_str(getattr(response, "text", ""), "")
        parsed = extract_json_object(raw_text)
        data = validate_model_output(parsed)
    except Exception as e:
        raise RuntimeError(f"Errore nella generazione o nel parsing Gemini: {e}")

    try:
        supabase.table("posts").update({"ticker": data["ticker"]}).eq("id", post_id).execute()
    except Exception as e:
        raise RuntimeError(f"Errore aggiornando il ticker del post: {e}")

    for c in data["commenti"]:
        ritardo = random.randint(5, 90)
        pub_date = now_utc() + timedelta(seconds=ritardo)

        payload = {
            "post_id": post_id,
            "username": c["user"],
            "personality": c["mood"],
            "comment_text": c["text"],
            "reply_to": c["reply_to"],
            "scheduled_at": pub_date.isoformat()
        }

        try:
            supabase.table("comments").insert(payload).execute()
        except Exception:
            continue


# =========================================================
# THREADING COMMENTI
# =========================================================
def build_threaded_comments(comments: list) -> list:
    if not comments:
        return []

    threaded = []
    processed_ids = set()
    usernames_present = {c.get("username") for c in comments if c.get("username")}

    roots = [
        c for c in comments
        if not c.get("reply_to") or c.get("reply_to") not in usernames_present
    ]

    def walk(comment, level):
        comment_id = comment.get("id")
        if not comment_id or comment_id in processed_ids:
            return

        processed_ids.add(comment_id)

        enriched = dict(comment)
        enriched["thread_level"] = level
        threaded.append(enriched)

        replies = [
            r for r in comments
            if r.get("reply_to") == comment.get("username") and r.get("id") not in processed_ids
        ]

        replies.sort(key=lambda x: x.get("scheduled_at") or "")

        for r in replies:
            walk(r, level + 1)

    roots.sort(key=lambda x: x.get("scheduled_at") or "")

    for root in roots:
        walk(root, 0)

    for c in comments:
        if c.get("id") not in processed_ids:
            walk(c, 0)

    return threaded


# =========================================================
# DB HELPERS
# =========================================================
def crea_post(content: str):
    res = supabase.table("posts").insert({"content": content}).execute()
    if not res.data:
        raise RuntimeError("Inserimento post fallito")
    return res.data[0]["id"]


def get_posts(limit=10):
    res = (
        supabase.table("posts")
        .select("*")
        .order("created_at", desc=True)
        .limit(limit)
        .execute()
    )
    return res.data or []


def get_visible_comments(post_id: str):
    current_time = now_utc().isoformat()
    res = (
        supabase.table("comments")
        .select("*")
        .eq("post_id", post_id)
        .lte("scheduled_at", current_time)
        .order("scheduled_at")
        .execute()
    )
    return res.data or []


def warn_comment(comment_id: str):
    supabase.table("comments").update({"is_warned": True}).eq("id", comment_id).execute()


# =========================================================
# UI SIDEBAR
# =========================================================
st.title("🏛️ Elite Finance Summit")

with st.sidebar:
    st.header("⚙️ Pannello Admin")
    input_news = st.text_area("Incolla un Link o una News:")
    password = st.text_input("Password Admin", type="password")

    if st.button("🚀 Lancia il Dibattito"):
        if password != "Riccardo74$":
            st.error("❌ Password errata!")
        elif not input_news.strip():
            st.warning("⚠️ Inserisci un link o un testo.")
        else:
            with st.spinner("I titani stanno scrivendo..."):
                try:
                    testo_da_analizzare = prepara_testo_da_analizzare(input_news)
                    post_id = crea_post(input_news)
                    genera_summit(testo_da_analizzare, post_id)
                    st.success("Thread lanciato! Guarda la bacheca.")
                    st.rerun()
                except Exception as e:
                    st.error(f"Errore durante la generazione del thread: {e}")

    st.divider()
    st.subheader("🧹 Gestione Dati")

    if st.button("🗑️ Svuota tutto il Forum"):
        if password != "Riccardo74$":
            st.error("❌ Serve la password per svuotare!")
        else:
            with st.spinner("Piallatura in corso..."):
                supabase.table("posts").delete().neq(
                    "id", "00000000-0000-0000-0000-000000000000"
                ).execute()
                st.success("Boom! Forum svuotato, pulito come nuovo.")
                st.rerun()


# =========================================================
# FEED FORUM
# =========================================================
posts = get_posts(limit=st.session_state.visible_posts)

for p in posts:
    post_id = p.get("id")
    ticker = p.get("ticker")
    content = p.get("content", "")
    created_at = format_created_at(p.get("created_at", ""))

    with st.container(border=True):
        if ticker and ticker != "NONE":
            c_news, c_graph = st.columns([1, 1.5])

            with c_news:
                st.caption(f"📅 Pubblicato il: {created_at}")
                st.info(content)

            with c_graph:
                mostra_grafico(ticker, chart_id=f"tv_chart_{post_id}")
        else:
            st.caption(f"📅 Pubblicato il: {created_at}")
            st.info(content)

        st.divider()

        coms = get_visible_comments(post_id)

        if not coms:
            st.write("⏱️ *Attendi qualche secondo... i primi commenti stanno per apparire.*")
        else:
            threaded_comments = build_threaded_comments(coms)

            for c in threaded_comments:
                level = c.get("thread_level", 0)
                is_reply = level > 0
                is_warned = bool(c.get("is_warned", False))
                username = c.get("username", "Sconosciuto")
                personality = c.get("personality", "Bearish")
                comment_text = c.get("comment_text", "")
                reply_to = c.get("reply_to")
                comment_id = c.get("id")

                if is_reply:
                    left_pad = min(0.06 * level, 0.30)
                    cols = st.columns([left_pad, 1 - left_pad])
                    chat_box = cols[1]
                else:
                    chat_box = st.container()

                with chat_box:
                    box_style = ""
                    if is_warned:
                        box_style = "border-left: 4px solid red; background: rgba(255,0,0,0.05);"

                    st.markdown(
                        f'<div style="{box_style} padding:5px; margin-bottom:5px; border-radius:8px;">',
                        unsafe_allow_html=True
                    )

                    with st.chat_message(
                        "user",
                        avatar=f"https://api.dicebear.com/7.x/bottts/svg?seed={username}"
                    ):
                        t_col, b_col = st.columns([0.85, 0.15])

                        with t_col:
                            if is_warned:
                                st.error(f"🚨 RICHIAMO DISCIPLINARE PER {username.upper()}")

                            if is_reply and reply_to:
                                st.markdown(f"↪️ *In risposta a **@{reply_to}***")

                            st.write(f"**{username}** ({personality}): {comment_text}")

                        with b_col:
                            if not is_warned and comment_id:
                                if st.button("🚫", key=f"w_{comment_id}"):
                                    warn_comment(comment_id)
                                    st.rerun()

                    st.markdown("</div>", unsafe_allow_html=True)


if len(posts) == st.session_state.visible_posts:
    st.divider()
    if st.button("Carica altri post"):
        st.session_state.visible_posts += 10
        st.rerun()