File size: 12,652 Bytes
2202957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import re
import streamlit as st
from datetime import datetime

def calculate_advanced_stability(all_wheel_data, formations, start_idx, end_idx, min_sorte, max_sorte):
    if not all_wheel_data or not formations:
        return []

    sorte_names = {1: "Estratto", 2: "Ambo", 3: "Terno", 4: "Quaterna", 5: "Cinquina"}
    results = []
    
    max_history = min(len(data) for data in all_wheel_data.values())
    s_idx = max(0, start_idx)
    e_idx = min(max_history, end_idx)
    
    total_draws = e_idx - s_idx
    if total_draws <= 0:
        return []

    for formation in formations:
        f_set = set(formation)
        hits_by_sorte = {s: 0 for s in range(min_sorte, max_sorte + 1)}
        current_delays = {s: 0 for s in range(min_sorte, max_sorte + 1)}
        found_first = {s: False for s in range(min_sorte, max_sorte + 1)}
        
        for i in range(s_idx, e_idx):
            combined_draw = set()
            for w in all_wheel_data:
                combined_draw.update(all_wheel_data[w][i])
            
            num_hits = len(combined_draw.intersection(f_set))
            
            for s in range(min_sorte, max_sorte + 1):
                if num_hits >= s:
                    hits_by_sorte[s] += 1
                    if not found_first[s]:
                        current_delays[s] = i - s_idx
                        found_first[s] = True
        
        f_stats = {
            'formazione': "-".join(map(str, sorted(formation))),
            'count': len(formation)
        }
        for s in range(min_sorte, max_sorte + 1):
            name = sorte_names[s]
            f_stats[f'{name} %'] = (hits_by_sorte[s] / total_draws * 100)
            f_stats[f'Rit. {name}'] = current_delays[s] if found_first[s] else total_draws
            
        results.append(f_stats)
    return results

def verify_bets(last_draws, text_input):
    city_map = {
        'BA': 'BA', 'BARI': 'BA', 'CA': 'CA', 'CAGLIARI': 'CA',
        'FI': 'FI', 'FIRENZE': 'FI', 'GE': 'GE', 'GENOVA': 'GE',
        'MI': 'MI', 'MILANO': 'MI', 'NA': 'NA', 'NAPOLI': 'NA',
        'PA': 'PA', 'PALERMO': 'PA', 'RO': 'RO', 'RM': 'RO', 'ROMA': 'RO',
        'TO': 'TO', 'TORINO': 'TO', 'VE': 'VE', 'VENEZIA': 'VE',
        'NZ': 'NZ', 'NAZ': 'NZ', 'NAZIONALE': 'NZ',
        'TUT': 'ALL', 'TUTTE': 'ALL', 'ALL': 'ALL'
    }

    tokens = re.sub(r'[^a-zA-Z0-9\s]', ' ', text_input).upper().split()
    hit_tracker = {code: [] for code in last_draws.keys()}
    current_wheels = []
    
    for token in tokens:
        if token in city_map:
            val = city_map[token]
            current_wheels = list(last_draws.keys()) if val == 'ALL' else [val]
        elif token.isdigit():
            num = int(token)
            targets = current_wheels if current_wheels else list(last_draws.keys())
            for wheel in targets:
                if wheel in last_draws and num in last_draws[wheel]:
                    if num not in hit_tracker[wheel]:
                        hit_tracker[wheel].append(num)
                        
    results = []
    for wheel, numbers in hit_tracker.items():
        if numbers:
            count = len(numbers)
            labels = ["ESTRATTO", "AMBO", "TERNO", "QUATERNA", "CINQUINA"]
            label = labels[min(count-1, 4)]
            results.append({'wheel': wheel, 'label': label, 'numbers': numbers, 'count': count})
    return results

def render_wheel_grid(all_wheel_data, history_idx, matched_numbers_by_wheel=None):
    cols = st.columns(4)
    wheel_order = ['BA', 'CA', 'FI', 'GE', 'MI', 'NA', 'PA', 'RO', 'TO', 'VE', 'NZ']
    
    for i, w_code in enumerate(wheel_order):
        with cols[i % 4]:
            if w_code in all_wheel_data and len(all_wheel_data[w_code]) > history_idx:
                nums = all_wheel_data[w_code][history_idx]
                matched = matched_numbers_by_wheel.get(w_code, []) if matched_numbers_by_wheel else []
                
                # HTML for numbers, handling 0 as "abbuio" (hidden/dimmed)
                num_html = []
                for n in nums:
                    if n == 0:
                        # "Abbuio" effect: empty circle or very dimmed
                        num_html.append('<div style="width: 28px; height: 28px; border-radius: 50%; background: rgba(255,255,255,0.05); color: transparent; display: flex; align-items: center; justify-content: center; border: 1px dashed rgba(255,255,255,0.1);"></div>')
                    else:
                        bg = "linear-gradient(135deg, #22c55e, #16a34a)" if n in matched else "linear-gradient(145deg, #ffffff, #e2e8f0)"
                        color = "white" if n in matched else "#0f172a"
                        border = "1px solid #fff" if n in matched else "none"
                        num_html.append(f'<div style="width: 28px; height: 28px; border-radius: 50%; background: {bg}; color: {color}; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 0.8em; box-shadow: inset 0 2px 4px rgba(255,255,255,0.5); border: {border}">{n}</div>')

                st.markdown(f"""

                    <div style="background: rgba(255,255,255,0.05); border-radius: 12px; padding: 10px; border: 1px solid rgba(255,255,255,0.1); margin-bottom: 10px;">

                        <div style="font-size: 0.9em; font-weight: bold; color: #e2e8f0; margin-bottom: 8px; text-transform: uppercase; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 3px;">{w_code}</div>

                        <div style="display: flex; justify-content: space-between;">

                            {' '.join(num_html)}

                        </div>

                    </div>

                """, unsafe_allow_html=True)

def run_jarvis_module(all_wheel_data, wheels_list, extraction_dates=None):
    st.markdown("""

        <style>

        .jarvis-card { background-color: #1e293b; padding: 15px; border-radius: 10px; border: 1px solid #334155; margin-bottom: 15px; }

        .win-badge { padding: 3px 10px; border-radius: 15px; font-weight: bold; font-size: 0.75em; text-transform: uppercase; }

        </style>

    """, unsafe_allow_html=True)

    st.header("🤖 Modulo Jarvis (Advanced Restoration)")
    
    tab_stab, tab_ver = st.tabs(["🔍 Stabilità Avanzata", "✅ Verifica Giocate"])
    
    with tab_stab:
        st.subheader("Configurazione Analisi")
        col_file, col_opts = st.columns([1, 1])
        with col_file:
            uploaded_file = st.file_uploader("Carica formazioni (.txt)", type=["txt"], key="stab_file")
            
            # Gestione session state per input manuale/file
            if "stab_text_input" not in st.session_state:
                st.session_state.stab_text_input = "1.4.9.11.13.16.17.23.25.26.30.40.42.49.55.58.59.61.67.68.73.77.81.83.85.86.88.89.90"
            
            if uploaded_file:
                st.session_state.stab_text_input = uploaded_file.read().decode('utf-8')
            
            manual_input = st.text_area("Oppure incolla qui", value=st.session_state.stab_text_input, height=100, key="stab_area")
            st.session_state.stab_text_input = manual_input
            
            formations = []
            for line in manual_input.splitlines():
                nums = [int(n) for n in re.findall(r'\d+', line) if 1 <= int(n) <= 90]
                if nums: formations.append(nums)
        with col_opts:
            max_h = min(len(d) for d in all_wheel_data.values()) if all_wheel_data else 10000
            range_mode = st.radio("Range", ["Ultime N", "Range Pers."], horizontal=True)
            if range_mode == "Ultime N":
                n_draws = st.number_input("Estrazioni", 1, max_h, max_h)
                start_i, end_i = 0, n_draws
            else:
                start_i = st.number_input("Da indice", 0, max_h-1, 0)
                end_i = st.number_input("A indice", start_i+1, max_h, max_h)
            col_s1, col_s2 = st.columns(2)
            sorte_min = col_s1.selectbox("Min Sorte", [1, 2, 3, 4, 5], index=1)
            sorte_max = col_s2.selectbox("Max Sorte", [1, 2, 3, 4, 5], index=2)
            rs_threshold = st.slider("Filtro Stabilità %", 0, 100, 0)
            
        if st.button("🚀 Esegui Analisi"):
            if formations:
                results = calculate_advanced_stability(all_wheel_data, formations, start_i, end_i, sorte_min, sorte_max)
                if results:
                    df = pd.DataFrame(results)
                    sorte_key = f"{ {1:'Estratto', 2:'Ambo', 3:'Terno', 4:'Quaterna', 5:'Cinquina'}[sorte_min] } %"
                    if rs_threshold > 0: df = df[df[sorte_key] >= rs_threshold]
                    st.dataframe(df.style.background_gradient(subset=[c for c in df.columns if '%' in c], cmap='Blues'), width="stretch")

    with tab_ver:
        st.subheader("Verifica Giocate & Griglia Ruote")
        
        # --- SELETTORE STORICO CON DATE ---
        max_draws = min(len(d) for d in all_wheel_data.values()) if all_wheel_data else 1
        
        # Formattazione label date
        def date_label(i):
            if extraction_dates and i < len(extraction_dates):
                return extraction_dates[i]
            return f"Indice {i}"

        hist_idx = st.select_slider(
            "Seleziona estrazione (Data o Indice)",
            options=list(range(max_draws)),
            format_func=date_label,
            value=0,
            help="Sposta il cursore per verificare giocate su date passate."
        )
        
        col_v1, col_v2 = st.columns([2, 1])
        with col_v2:
            auto_mode = st.checkbox("🔄 Verifica real-time (Auto)", value=True, key="auto_verify_v2")
            uploaded_ver_file = st.file_uploader("Carica file giocate (.txt)", type=["txt"], key="ver_file_v2")
            
            # Caricamento file txt nella text area
            file_content = ""
            if uploaded_ver_file:
                file_content = uploaded_ver_file.read().decode('utf-8')
                
            btn_verify = st.button("🎯 VERIFICA ORA", width="stretch", key="btn_ver_v2")
            st.caption("Scorciatoia: Premi fuori dal campo o CTRL+INVIO")
        
        with col_v1:
            if "bet_text_input" not in st.session_state:
                st.session_state.bet_text_input = ""
            
            if uploaded_ver_file:
                st.session_state.bet_text_input = uploaded_ver_file.read().decode('utf-8')
                
            bet_input = st.text_area("Incolla qui le giocate", value=st.session_state.bet_text_input, height=150, key="bet_area_v2")
            st.session_state.bet_text_input = bet_input

        # LOGICA VERIFICA
        vincite = []
        matched_map = {}
        if bet_input and (auto_mode or btn_verify):
            target_draws = {w: all_wheel_data[w][hist_idx] for w in all_wheel_data if len(all_wheel_data[w]) > hist_idx}
            vincite = verify_bets(target_draws, bet_input)
            for v in vincite:
                matched_map[v['wheel']] = v['numbers']

        if vincite:
            st.success(f"🎊 Rilevate {len(vincite)} vincite per {date_label(hist_idx)}!")
            # Design più compatto per risultati multipli
            cols_res = st.columns(min(len(vincite), 4))
            for idx, v in enumerate(vincite):
                with cols_res[idx % 4]:
                    color = "#3b82f6" if v['count'] == 1 else "#10b981" if v['count'] == 2 else "#8b5cf6"
                    st.markdown(f"""

                        <div class="jarvis-card" style="border-left: 4px solid {color}; padding: 10px;">

                            <span class="win-badge" style="background-color: {color}; color: white; display: block; text-align: center; margin-bottom: 5px;">{v['label']}</span>

                            <div style="font-weight: bold; color: #fff; text-align: center;">{v['wheel']}</div>

                            <div style="font-size: 1.1em; color: #60a5fa; text-align: center;">{", ".join(map(str, v['numbers']))}</div>

                        </div>

                    """, unsafe_allow_html=True)
        elif bet_input:
            st.info(f"Nessuna vincita rilevata per {date_label(hist_idx)}.")

        st.divider()
        st.markdown(f"#### 🎰 Tabellone Estrazione: {date_label(hist_idx)}")
        render_wheel_grid(all_wheel_data, hist_idx, matched_map)