File size: 26,421 Bytes
d4c51f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ae913
ffbe64b
d4c51f2
ffbe64b
 
 
 
 
 
 
 
d4c51f2
 
 
 
ffbe64b
 
d4c51f2
ffbe64b
 
 
d4c51f2
 
 
ffbe64b
d4c51f2
ffbe64b
d4c51f2
ffbe64b
d4c51f2
ffbe64b
 
d4c51f2
 
ffbe64b
d4c51f2
 
 
 
 
 
ffbe64b
d4c51f2
 
ffbe64b
d4c51f2
 
f9ae913
 
1e79652
 
f9ae913
 
 
 
9a1d517
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e79652
 
 
 
 
 
 
 
 
 
 
d4c51f2
 
 
 
 
 
a6ea912
d4c51f2
a6ea912
d4c51f2
 
 
 
 
 
 
 
 
 
 
 
 
 
ffbe64b
 
 
 
 
 
 
1e79652
 
 
 
ffbe64b
 
 
 
 
 
 
 
 
1e79652
 
 
 
 
 
 
 
 
 
 
 
 
d4c51f2
 
1e79652
 
 
 
 
 
 
 
 
 
 
 
 
d4c51f2
 
9a1d517
d4c51f2
 
 
 
 
 
1e79652
 
 
 
 
 
 
 
9a1d517
1e79652
 
 
 
 
 
 
d4c51f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e79652
 
 
 
 
 
 
d4c51f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03022c2
d4c51f2
03022c2
d4c51f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e79652
 
 
 
 
 
 
d4c51f2
 
 
03022c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c51f2
 
f9ae913
d4c51f2
f9ae913
 
 
d4c51f2
 
 
 
 
 
 
 
03022c2
 
1e79652
d4c51f2
 
 
 
 
 
 
 
 
 
f9ae913
 
 
d4c51f2
 
 
 
 
 
 
 
 
f9ae913
 
d4c51f2
 
 
 
9916b96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c51f2
 
9916b96
 
d4c51f2
 
 
ffbe64b
f9ae913
d4c51f2
 
 
 
1e79652
 
 
 
 
 
d4c51f2
 
ffbe64b
 
 
9a1d517
ffbe64b
 
9a1d517
 
ffbe64b
 
 
 
 
 
9a1d517
ffbe64b
 
 
9a1d517
ffbe64b
 
 
9a1d517
 
ffbe64b
 
 
 
 
 
 
d4c51f2
 
 
 
ffbe64b
d4c51f2
 
 
 
 
 
ffbe64b
 
d4c51f2
 
 
 
 
 
 
 
 
9a1d517
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c51f2
 
 
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
"""Flask app β€” the shippable front end.

Routes:
  /                landing + "paste a wallet" scorer form + email capture
  /score           GET ?wallet=0x… -> live consistency score card (lead magnet)
  /digest          latest daily digest rendered as HTML (SEO surface)
  /subscribe       POST email -> data/subscribers.csv

Run:
  cd polymarket-copytrade && source .venv/bin/activate
  python webapp/app.py            # http://127.0.0.1:5000
"""
from __future__ import annotations

import csv
import re
import os
import sys
from datetime import datetime, timezone
from html import escape
from pathlib import Path

_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(_ROOT))
os.chdir(_ROOT)   # so config.yaml + data/ resolve regardless of launch cwd

from flask import Flask, request, redirect, url_for

from pmct.client import PolymarketClient
from pmct.score import score_wallet
from pmct.util import load_config, cache_path

app = Flask(__name__)
_cfg = load_config()
_client = PolymarketClient(sleep_sec=0.1)

BRAND = "SharpFlow"
TAGLINE = "The Polymarket smart-money tracker whale trackers miss."

CSS = """
:root{--bg:#0a0f14;--card:#111820;--ink:#e6edf3;--mut:#7d8da0;--body:#c7d0dc;--acc:#22d3ee;
--acc2:#14b8a6;--warn:#d29922;--bad:#f85149;--line:#1c2531;--inset:#0c131b}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);
font:16px/1.55 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
background-image:radial-gradient(900px 500px at 80% -10%,rgba(34,211,238,.10),transparent 70%),
radial-gradient(700px 400px at -10% 10%,rgba(20,184,166,.08),transparent 70%)}
a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline}
.wrap{max-width:820px;margin:0 auto;padding:32px 20px}
.brand{font-weight:800;font-size:22px;letter-spacing:-.02em}
.brand span{background:linear-gradient(135deg,var(--acc),var(--acc2));
-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}
.hero{margin:28px 0 10px}.hero h1{font-size:34px;line-height:1.15;margin:0 0 10px;letter-spacing:-.02em}
.hero p{color:var(--mut);font-size:18px;margin:0}
.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:22px;margin:18px 0}
input[type=text],input[type=email]{width:100%;padding:13px 14px;border-radius:10px;
border:1px solid var(--line);background:var(--inset);color:var(--ink);font-size:15px}
input:focus{outline:none;border-color:var(--acc);box-shadow:0 0 0 3px rgba(34,211,238,.15)}
.row{display:flex;gap:10px;flex-wrap:wrap}.row>*{flex:1;min-width:180px}
button{background:linear-gradient(135deg,var(--acc),var(--acc2));color:#04121a;border:0;
border-radius:10px;padding:13px 18px;font-weight:700;font-size:15px;cursor:pointer;
white-space:nowrap;flex:0 0 auto}button:hover{filter:brightness(1.08)}
button.ghost{background:transparent;color:var(--ink);border:1px solid var(--line)}
.mut{color:var(--mut)}.small{font-size:13px}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
.tag{display:inline-block;padding:3px 10px;border-radius:999px;font-size:12px;font-weight:700}
.tag.watch{background:#0c3138;color:var(--acc)}.tag.whale{background:#3a2f10;color:var(--warn)}
.tag.maker{background:#3a1414;color:var(--bad)}.tag.inconsistent{background:#2a2033;color:#c98bff}
.tag.thin,.tag.bad{background:#1a222c;color:var(--mut)}
.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:14px}
.metric{background:var(--inset);border:1px solid var(--line);border-radius:10px;padding:12px}
.metric .k{color:var(--mut);font-size:12px}.metric .v{font-size:20px;font-weight:700;margin-top:2px}
.bar{height:8px;background:var(--inset);border-radius:6px;overflow:hidden;margin-top:6px}
.bar>i{display:block;height:100%;background:linear-gradient(90deg,var(--acc),var(--acc2))}
table{border-collapse:collapse;width:100%;font-size:14px}th,td{border-bottom:1px solid var(--line);
padding:8px 6px;text-align:left}th{color:var(--mut);font-weight:600}
tbody tr:hover{background:rgba(34,211,238,.04)}
.foot{color:var(--mut);font-size:12px;margin-top:26px;border-top:1px solid var(--line);padding-top:16px}
.pill{border:1px solid var(--line);border-radius:999px;padding:4px 12px;font-size:13px;color:var(--mut)}
.nav{display:flex;align-items:center;justify-content:space-between;gap:16px;
padding-bottom:12px;border-bottom:1px solid var(--line)}
.nav .brand{text-decoration:none;color:var(--ink)}
.navlinks{display:flex;gap:20px}.navlinks a{color:var(--mut);font-weight:600;font-size:14px}
.navlinks a:hover{color:var(--acc);text-decoration:none}
.examples{margin-top:14px;display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.exlabel{color:var(--mut);font-size:13px;margin-right:2px}
.chip{border:1px solid var(--line);background:var(--inset);border-radius:999px;
padding:6px 12px;font-size:13px;color:var(--ink)}
.chip:hover{border-color:var(--acc);color:var(--acc)}
ul.explain{margin:10px 0 0;padding-left:20px}ul.explain li{margin:10px 0;color:var(--body);
line-height:1.65;max-width:64ch}ul.explain b{color:var(--ink)}
.tscroll{overflow-x:auto;-webkit-overflow-scrolling:touch}
.tscroll table{min-width:520px}
.digest p{color:var(--body);line-height:1.7;max-width:66ch;margin:12px 0}
.digest h2{font-size:19px;margin:28px 0 6px;letter-spacing:-.01em}
.digest h2:first-child{margin-top:4px}
.digest .lead{font-size:15px;color:var(--mut);margin:0 0 6px}
.tiers{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin:18px 0}
.tier{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:22px;
display:flex;flex-direction:column}
.tier.feat{border-color:var(--acc);box-shadow:inset 0 0 0 1px var(--acc)}
.tier h3{margin:0;font-size:18px}
.tier .price{font-size:30px;font-weight:800;letter-spacing:-.02em;margin:8px 0 0}
.tier .price small{font-size:14px;font-weight:600;color:var(--mut)}
.tier .soon{display:inline-block;margin:8px 0 0;font-size:12px;font-weight:700;
color:var(--acc);background:#0c3138;padding:3px 10px;border-radius:999px}
.tier .live{display:inline-block;margin:8px 0 0;font-size:12px;font-weight:700;
color:var(--acc2);background:#0c2c28;padding:3px 10px;border-radius:999px}
.tier ul.feats{list-style:none;margin:14px 0 18px;padding:0;flex:1}
.tier ul.feats li{margin:9px 0;padding-left:22px;position:relative;color:var(--body);line-height:1.5}
.tier ul.feats li:before{content:'\\2713';position:absolute;left:0;color:var(--acc);font-weight:700}
.tier .cta{margin-top:auto}
@media (max-width:760px){.tiers{grid-template-columns:1fr}}
@media (max-width:640px){
.wrap{padding:20px 14px}
.hero h1{font-size:26px}.hero p{font-size:16px}
.card{padding:16px}
.grid{grid-template-columns:1fr 1fr}
.navlinks{gap:14px}.navlinks a{font-size:13px}
.brand{font-size:19px}
button{width:100%}.row>*{min-width:100%}
table{font-size:13px}th,td{padding:7px 5px}
}
@media (max-width:380px){.grid{grid-template-columns:1fr}}
"""

# Real wallets that showcase the product's judgement β€” one to follow, one too big
# to mirror, one uncopyable. Doubles as the "try it" hook so a first-time visitor
# never dead-ends on a random address with no Polymarket history.
EXAMPLES = [
    ("Consistent mid-size", "0x28059b3fb7af7ed76d83dc9121bbb72ec7cf76ed"),
    ("Mega-whale", "0xd235973291b2b75ff4070e9c0b01728c520b0f29"),
    ("Market-maker", "0x5d189e816b4149be00977c1a3c8840374aec4972"),
]


def example_chips(label: str = "Try a real trader:") -> str:
    chips = "".join(
        f'<a class=chip href="/score?wallet={w}">{escape(t)}</a>' for t, w in EXAMPLES
    )
    return f'<div class=examples><span class=exlabel>{escape(label)}</span>{chips}</div>'

TAGLABEL = {"watch": "WORTH WATCHING", "whale": "MEGA-WHALE",
            "maker": "MARKET-MAKER", "inconsistent": "INCONSISTENT",
            "thin": "TOO THIN", "bad": "INVALID"}


DIGEST_EXPLAINER = """
<div class=hero><h1>Daily smart-money digest</h1>
<p>The mid-size Polymarket traders who win consistently β€” and the boldest bets they
just made.</p></div>
<div class=card><h3 style="margin:0 0 8px">What am I looking at?</h3>
<ul class=explain>
<li><b>Top moves right now</b> β€” the highest-signal bets our tracked traders placed
recently. <b>Signal</b> blends the trader's track record with how big this bet is
<i>for them</i> (conviction) and how far the price is from a coin-flip (edge). The
dots are a <b>relative rank of today's moves</b> β€” ●●●●● = strongest in the list,
●○○○○ = weakest.</li>
<li><b>The traders we're tracking</b> β€” the vetted wallets themselves. These are
<b>mid-size traders whale trackers skip</b> (not $10k+ whales, not market-makers),
scored on consistency, repeatability and copyability β€” <i>not</i> size. Tap any
address to verify it live on Polymarket.</li>
</ul>
<p class="mut small" style="margin:10px 0 0">Flow intelligence, not financial advice.</p></div>
"""


SITE_URL = "https://sharpflowapp-web.hf.space"
JSONLD = (
    '{"@context":"https://schema.org","@type":"WebApplication",'
    '"name":"SharpFlow","applicationCategory":"FinanceApplication",'
    '"operatingSystem":"Web","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},'
    '"description":"Score any Polymarket wallet and follow consistent mid-size smart-money '
    'traders that whale trackers miss.","url":"' + SITE_URL + '"}'
)


def page(title: str, body: str, desc: str = "", path: str = "/") -> str:
    desc = desc or TAGLINE
    canon = SITE_URL + path
    return f"""<!doctype html><html lang=en><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>{escape(title)}</title>
<meta name=description content="{escape(desc)}">
<link rel=canonical href="{escape(canon, quote=True)}">
<meta name=robots content="index,follow">
<meta property="og:type" content="website">
<meta property="og:site_name" content="{BRAND}">
<meta property="og:title" content="{escape(title)}">
<meta property="og:description" content="{escape(desc)}">
<meta property="og:url" content="{escape(canon, quote=True)}">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="{escape(title)}">
<meta name="twitter:description" content="{escape(desc)}">
<script type="application/ld+json">{JSONLD}</script>
<style>{CSS}</style></head><body><div class=wrap>
<div class=nav><a class=brand href="/"><span>β—†</span> {BRAND}</a>
<div class=navlinks><a href="/">Score a wallet</a><a href="/digest">Daily digest</a><a href="/pricing">Pricing</a></div></div>
{body}
<div class=foot>Built from Polymarket public data. <b>Flow intelligence, not financial
advice.</b> Consistency scoring β‰  guaranteed profit. Past performance is not predictive.</div>
</div></body></html>"""


@app.route("/robots.txt")
def robots():
    return (f"User-agent: *\nAllow: /\nSitemap: {SITE_URL}/sitemap.xml\n",
            200, {"Content-Type": "text/plain"})


@app.route("/sitemap.xml")
def sitemap():
    urls = ["/", "/digest", "/pricing"]
    items = "".join(f"<url><loc>{SITE_URL}{u}</loc></url>" for u in urls)
    xml = ('<?xml version="1.0" encoding="UTF-8"?>'
           '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
           f"{items}</urlset>")
    return xml, 200, {"Content-Type": "application/xml"}


def scorer_form(prefill: str = "") -> str:
    return f"""<form action="/score" method=get class=row>
<input type=text name=wallet placeholder="Paste a Polymarket wallet: 0x…"
 value="{escape(prefill)}" autocomplete=off spellcheck=false>
<button type=submit>Score it β†’</button></form>"""


@app.route("/")
def home():
    body = f"""
<div class=hero><h1>{escape(TAGLINE)}</h1>
<p>Paste any <b>Polymarket wallet</b> and we score it β€” consistent smart money, a whale,
a market-maker, or just lucky. Every tracker flags $10k whales; we surface the
<b>consistent mid-size Polymarket traders</b> they skip.</p></div>
<div class=card><h3 style="margin:0 0 12px">Score any wallet β€” free</h3>
{scorer_form()}
{example_chips()}
<p class="mut small" style="margin:12px 0 0">Paste any Polymarket address. We read its
history and tell you: consistent & copyable, a whale, a market-maker, or just lucky.</p>
</div>
<div class=card><h3 style="margin:0 0 8px">Get the daily digest</h3>
<p class="mut" style="margin:0 0 12px">The top consistent traders and their highest-conviction
moves, once a day. Free tier delayed 24h.</p>
<form action="/subscribe" method=post class=row>
<input type=email name=email placeholder="you@email.com" required>
<button type=submit>Subscribe free</button></form></div>
"""
    return page(
        f"{BRAND} β€” Polymarket smart-money tracker & free wallet score",
        body,
        desc="Score any Polymarket wallet free, and follow consistent mid-size "
             "smart-money traders that whale trackers miss. Flow intelligence, not "
             "financial advice.",
        path="/")


@app.route("/score")
def score():
    wallet = (request.args.get("wallet") or "").strip()
    if not wallet:
        return redirect(url_for("home"))
    r = score_wallet(_client, wallet)
    if not r.ok:
        body = f"""<div class=hero><h1>Nothing to score here</h1>
<p>{escape(r.note)} This wallet has no Polymarket trading history we can read β€”
try a real trader below.</p></div>
<div class=card>{scorer_form(wallet)}
{example_chips("Or try one of these:")}</div>"""
        return page(f"{BRAND} β€” score", body)

    tag = r.verdict_tag or "thin"
    pct = int(round(r.trader_score * 100))
    short = f"{r.wallet[:8]}…{r.wallet[-6:]}"
    prof = f"https://polymarket.com/profile/{r.wallet}"
    body = f"""
<div class=hero><a class="pill mono" href="{escape(prof, quote=True)}" target=_blank rel=noopener title="Verify on Polymarket" style="display:inline-block;margin-bottom:10px;text-decoration:none">{escape(r.wallet)} β†—</a>
<h1 style="margin:6px 0">Trader score: {r.trader_score:.2f}
<span class="tag {tag}">{TAGLABEL.get(tag,tag.upper())}</span></h1>
<div class=bar style="max-width:360px"><i style="width:{pct}%"></i></div>
<p style="margin-top:14px">{escape(r.verdict)}</p></div>
<div class=grid>
<div class=metric><div class=k>Consistency (green months)</div><div class=v>{r.monthly_profit_ratio:.0%}</div></div>
<div class=metric><div class=k>Repeatability</div><div class=v>{r.repeatability:.2f}</div></div>
<div class=metric><div class=k>Copyable (1 βˆ’ rebate)</div><div class=v>{max(0,1-r.rebate_share):.0%}</div></div>
<div class=metric><div class=k>Reconstructed PnL</div><div class=v>${r.total_pnl:,.0f}</div></div>
<div class=metric><div class=k>Avg bet size</div><div class=v>${r.avg_trade_usdc:,.0f}</div></div>
<div class=metric><div class=k>Trades Β· resolved</div><div class=v>{r.n_trades:,} Β· {r.n_resolved_markets}</div></div>
</div>
<div class=card style="margin-top:18px"><b>Score another</b>{scorer_form()}</div>
<p class="mut small">{escape(r.note)}</p>
"""
    return page(
        f"{short} Polymarket wallet score {r.trader_score:.2f} β€” {BRAND}",
        body,
        desc=f"Polymarket wallet {short} scored {r.trader_score:.2f}: "
             f"{TAGLABEL.get(tag, tag).lower()}. Consistency, repeatability and "
             f"copyability β€” not size.",
        path="/score")


_TABLE_RE = re.compile(r"^\|(.+)\|\s*$")
_LINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^\s)]+)\)")
_BOLD_RE = re.compile(r"\*\*([^*]+)\*\*")


def _inline(text: str) -> str:
    """Escape text, then render inline **bold** and [label](https url) links.
    Links are restricted to http/https so escaped content stays injection-safe."""
    out, i = [], 0
    for mm in _LINK_RE.finditer(text):
        out.append(_bold(text[i:mm.start()]))
        label, url = mm.group(1), mm.group(2)
        out.append(f'<a href="{escape(url, quote=True)}" target=_blank rel=noopener>{escape(label)}</a>')
        i = mm.end()
    out.append(_bold(text[i:]))
    return "".join(out)


def _bold(text: str) -> str:
    parts, i = [], 0
    for mm in _BOLD_RE.finditer(text):
        parts.append(escape(text[i:mm.start()]))
        parts.append(f"<b>{escape(mm.group(1))}</b>")
        i = mm.end()
    parts.append(escape(text[i:]))
    return "".join(parts)


def _md_to_html(md: str, terse: bool = False) -> str:
    """Tiny markdown renderer: headings, tables, hr, paragraphs. Enough for our
    own digest output β€” not a general parser. In terse mode we drop the leading
    H1 and the italic-only legend paragraphs (the web page already explains those
    in the explainer card), so the render doesn't repeat itself."""
    out, rows = [], []

    def flush_table():
        if not rows:
            return
        cells = [[c.strip() for c in r.strip("|").split("|")] for r in rows]
        body = cells[2:] if len(cells) > 1 and set("".join(cells[1])) <= set("-: ") else cells[1:]
        head = cells[0]
        h = "".join(f"<th>{_inline(c)}</th>" for c in head)
        b = "".join("<tr>" + "".join(f"<td>{_inline(c)}</td>" for c in r) + "</tr>" for r in body)
        out.append(f"<div class=tscroll><table><thead><tr>{h}</tr></thead><tbody>{b}</tbody></table></div>")
        rows.clear()

    for ln in md.splitlines():
        if _TABLE_RE.match(ln):
            rows.append(ln)
            continue
        flush_table()
        s = ln.strip()
        if not s:
            continue
        italic_only = len(s) > 1 and s.startswith("_") and s.endswith("_")
        if terse and (s.startswith("# ") or s == "---" or italic_only):
            continue
        if s.startswith("### "):
            out.append(f"<h3>{escape(s[4:])}</h3>")
        elif s.startswith("## "):
            out.append(f"<h2>{escape(s[3:])}</h2>")
        elif s.startswith("# "):
            out.append(f"<h1>{escape(s[2:])}</h1>")
        elif s == "---":
            out.append("<hr style='border:0;border-top:1px solid var(--line)'>")
        else:
            cls = "lead" if terse else "mut"
            out.append(f"<p class={cls}>{_inline(s.replace('_', ''))}</p>")
    flush_table()
    return "\n".join(out)


DIGESTS_DATASET = "sharpflowapp/digests"
_digest_cache: dict = {"md": None, "ts": 0.0}
_DIGEST_TTL = 300  # seconds β€” the daily cron only publishes once/day


def _local_digest_md() -> str | None:
    files = sorted(cache_path(_cfg, ".").glob("digest_*.md"))
    return files[-1].read_text(encoding="utf-8") if files else None


def _latest_digest_md() -> str | None:
    """Newest digest, fetched from the HF dataset (so publishing never rebuilds
    the Space) with a short TTL cache and a fallback to any baked-in seed file."""
    import time
    now = time.time()
    if _digest_cache["md"] is not None and now - _digest_cache["ts"] < _DIGEST_TTL:
        return _digest_cache["md"]
    md = None
    token = os.environ.get("HF_TOKEN")
    try:
        from huggingface_hub import HfApi, hf_hub_download
        names = [f for f in HfApi(token=token).list_repo_files(
                    DIGESTS_DATASET, repo_type="dataset")
                 if f.startswith("digest_") and f.endswith(".md")]
        if names:
            path = hf_hub_download(DIGESTS_DATASET, sorted(names)[-1],
                                   repo_type="dataset", token=token)
            md = Path(path).read_text(encoding="utf-8")
    except Exception:
        md = None
    if md is None:
        md = _local_digest_md()   # fallback: baked-in seed digest
    if md is not None:
        _digest_cache.update(md=md, ts=now)
    return md


@app.route("/digest")
def digest():
    md = _latest_digest_md()
    if not md:
        return page(f"{BRAND} β€” digest",
                    "<div class=hero><h1>No digest yet</h1>"
                    "<p class=mut>Run <code>python scripts/05_digest.py</code> to generate one.</p></div>")
    body = DIGEST_EXPLAINER \
           + f"<div class='card digest'>{_md_to_html(md, terse=True)}</div>" \
           f"<div class=card><b>Want it daily by email?</b>" \
           f"<form action='/subscribe' method=post class=row style='margin-top:10px'>" \
           f"<input type=email name=email placeholder='you@email.com' required>" \
           f"<button type=submit>Subscribe free</button></form></div>"
    return page(
        f"{BRAND} β€” Daily Polymarket smart-money digest",
        body,
        desc="The consistent mid-size Polymarket traders whale trackers skip, and "
             "their highest-conviction moves today β€” each scored for signal quality.",
        path="/digest")


SUBSCRIBERS_DATASET = "sharpflowapp/subscribers"


def _persist_subscriber(email: str, ts: str, kind: str = "digest") -> None:
    """Durably record a signup in a private HF dataset so it survives the Space's
    ephemeral filesystem. Append-only (one file per signup) to dodge races.
    `kind` tags intent (digest signup vs. a paid-tier waitlist) so we can measure
    willingness-to-pay. Best-effort: never let a storage hiccup break signup UX."""
    token = os.environ.get("HF_TOKEN")
    if not token:
        return
    try:
        import hashlib
        import io
        import re as _re

        from huggingface_hub import HfApi

        safe = _re.sub(r"[^a-z0-9_]+", "", kind.lower())[:24] or "digest"
        key = hashlib.sha1(email.encode()).hexdigest()[:12]
        api = HfApi(token=token)
        api.upload_file(
            path_or_fileobj=io.BytesIO(f"{email},{ts},{safe}\n".encode()),
            path_in_repo=f"emails/{ts[:10]}_{safe}_{key}.csv",
            repo_id=SUBSCRIBERS_DATASET,
            repo_type="dataset",
        )
    except Exception:
        pass


@app.route("/subscribe", methods=["POST"])
def subscribe():
    email = (request.form.get("email") or "").strip().lower()
    if "@" in email and "." in email:
        ts = datetime.now(timezone.utc).isoformat()
        path = cache_path(_cfg, "subscribers.csv")
        new = not path.exists()
        with path.open("a", newline="") as f:
            w = csv.writer(f)
            if new:
                w.writerow(["email", "ts_utc"])
            w.writerow([email, ts])
        _persist_subscriber(email, ts)
        msg = "You're in. First digest lands next run."
    else:
        msg = "That email didn't look right β€” try again."
    return page(f"{BRAND} β€” subscribed",
                f"<div class=hero><h1>{escape(msg)}</h1></div>"
                f"<div class=card>{scorer_form()}"
                f"<p class='mut small' style='margin-top:10px'>Meanwhile, score any wallet above.</p></div>")


def _waitlist_form(tier: str, cta: str) -> str:
    return (f"<form action='/waitlist' method=post class=cta>"
            f"<input type=hidden name=tier value='{escape(tier, quote=True)}'>"
            f"<input type=email name=email placeholder='you@email.com' required "
            f"style='margin-bottom:10px'>"
            f"<button type=submit style='width:100%'>{escape(cta)}</button></form>")


@app.route("/pricing")
def pricing():
    free_cta = (f"<form action='/subscribe' method=post class=cta>"
                f"<input type=email name=email placeholder='you@email.com' required "
                f"style='margin-bottom:10px'>"
                f"<button type=submit style='width:100%'>Get the free digest</button></form>")
    tiers = f"""
<div class=tiers>
  <div class=tier>
    <h3>Free</h3>
    <div class=price>$0</div>
    <span class=live>Live now</span>
    <ul class=feats>
      <li>Daily smart-money digest</li>
      <li>Top 5 consistent traders</li>
      <li>Signal score on every move</li>
      <li>Delivered ~24h delayed</li>
    </ul>
    {free_cta}
  </div>
  <div class="tier feat">
    <h3>Pro</h3>
    <div class=price>$19<small>/mo</small></div>
    <span class=soon>Coming soon Β· join waitlist</span>
    <ul class=feats>
      <li><b>Real-time</b> Telegram alerts</li>
      <li>All ~15 tracked traders (not just 5)</li>
      <li>Your own custom wallet watchlist</li>
      <li>No 24h delay</li>
    </ul>
    {_waitlist_form("pro", "Join the Pro waitlist")}
  </div>
  <div class=tier>
    <h3>Trader</h3>
    <div class=price>$49<small>/mo</small></div>
    <span class=soon>Coming soon Β· join waitlist</span>
    <ul class=feats>
      <li>Everything in Pro</li>
      <li>Webhook / API access</li>
      <li>Faster polling</li>
      <li>Backtest any trader on demand</li>
    </ul>
    {_waitlist_form("trader", "Join the Trader waitlist")}
  </div>
</div>"""
    body = f"""
<div class=hero><h1>Simple pricing</h1>
<p>Start free today. The paid tiers are in build β€” join a waitlist and you'll be first
in when real-time alerts go live, at this early-bird price.</p></div>
{tiers}
<div class=card><p class="mut small" style="margin:0">Flow intelligence, not financial
advice. Consistency scoring β‰  guaranteed profit. Waitlist just means we email you when
the tier opens β€” no charge, no card, unsubscribe anytime.</p></div>
"""
    return page(
        f"{BRAND} β€” Pricing",
        body,
        desc="SharpFlow pricing: a free daily Polymarket smart-money digest, plus Pro "
             "real-time alerts and a Trader API tier (coming soon β€” join the waitlist).",
        path="/pricing")


@app.route("/waitlist", methods=["POST"])
def waitlist():
    email = (request.form.get("email") or "").strip().lower()
    tier = (request.form.get("tier") or "pro").strip().lower()
    tier = tier if tier in ("pro", "trader") else "pro"
    if "@" in email and "." in email:
        ts = datetime.now(timezone.utc).isoformat()
        _persist_subscriber(email, ts, kind=f"waitlist_{tier}")
        msg = f"You're on the {tier.title()} waitlist."
        sub = ("We'll email you the moment it opens β€” at the early-bird price, no card "
               "needed now.")
    else:
        msg = "That email didn't look right β€” try again."
        sub = "Head back to pricing and re-enter it."
    return page(f"{BRAND} β€” waitlist",
                f"<div class=hero><h1>{escape(msg)}</h1><p>{escape(sub)}</p></div>"
                f"<div class=card><p class=mut style='margin:0 0 12px'>Meanwhile, the free "
                f"digest is live today:</p>"
                f"<form action='/subscribe' method=post class=row>"
                f"<input type=email name=email placeholder='you@email.com' required>"
                f"<button type=submit>Get the free digest</button></form></div>",
                path="/pricing")


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "5055"))
    app.run(host="127.0.0.1", port=port, debug=False)