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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
"""
Subscription detection engine.

Analyzes bank statement CSV transactions and identifies recurring subscription charges
using both heuristic rules (known merchants, cadence patterns) and pattern matching.

Privacy-first: all detection runs locally on HF compute. No data persisted.
"""

from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import List, Dict, Optional
import re
import io
import csv
from collections import defaultdict


# ─── Known subscription merchant fingerprints ────────────────────────

# Maps lowercase substring β†’ (canonical_name, category)
KNOWN_MERCHANTS = {
    # Streaming
    "netflix": ("Netflix", "streaming"),
    "hulu": ("Hulu", "streaming"),
    "disney+": ("Disney+", "streaming"),
    "disneyplus": ("Disney+", "streaming"),
    "hbo max": ("HBO Max", "streaming"),
    "max.com": ("Max", "streaming"),
    "paramount": ("Paramount+", "streaming"),
    "peacock": ("Peacock", "streaming"),
    "apple tv": ("Apple TV+", "streaming"),
    "spotify": ("Spotify", "music"),
    "apple music": ("Apple Music", "music"),
    "youtube premium": ("YouTube Premium", "music/streaming"),
    "youtube music": ("YouTube Music", "music"),
    "tidal": ("Tidal", "music"),
    "amazon prime": ("Amazon Prime", "shopping/streaming"),
    "audible": ("Audible", "audiobooks"),
    "kindle unlimited": ("Kindle Unlimited", "books"),

    # Software / SaaS
    "adobe": ("Adobe Creative Cloud", "software"),
    "microsoft 365": ("Microsoft 365", "software"),
    "office 365": ("Microsoft 365", "software"),
    "google one": ("Google One", "cloud"),
    "icloud": ("iCloud+", "cloud"),
    "dropbox": ("Dropbox", "cloud"),
    "notion": ("Notion", "productivity"),
    "figma": ("Figma", "software"),
    "github": ("GitHub", "software"),
    "openai": ("ChatGPT Plus", "ai"),
    "chatgpt": ("ChatGPT Plus", "ai"),
    "anthropic": ("Claude Pro", "ai"),
    "claude.ai": ("Claude Pro", "ai"),
    "midjourney": ("Midjourney", "ai"),
    "perplexity": ("Perplexity Pro", "ai"),

    # Fitness
    "peloton": ("Peloton", "fitness"),
    "apple fitness": ("Apple Fitness+", "fitness"),
    "classpass": ("ClassPass", "fitness"),
    "myfitnesspal": ("MyFitnessPal Premium", "fitness"),
    "strava": ("Strava Premium", "fitness"),

    # Mental health / wellness
    "headspace": ("Headspace", "wellness"),
    "calm.com": ("Calm", "wellness"),
    "betterhelp": ("BetterHelp", "wellness"),
    "talkspace": ("Talkspace", "wellness"),

    # Food / delivery
    "doordash dashpass": ("DoorDash DashPass", "food"),
    "uber one": ("Uber One", "transport/food"),
    "instacart+": ("Instacart+", "food"),
    "hellofresh": ("HelloFresh", "food"),
    "blue apron": ("Blue Apron", "food"),

    # News / media
    "nyt": ("NYTimes", "news"),
    "new york times": ("NYTimes", "news"),
    "wsj": ("WSJ", "news"),
    "wall street journal": ("WSJ", "news"),
    "washington post": ("Washington Post", "news"),
    "wapo": ("Washington Post", "news"),
    "patreon": ("Patreon (creator)", "creator"),
    "substack": ("Substack (publisher)", "creator"),
    "medium": ("Medium", "news"),

    # Dating
    "tinder": ("Tinder Plus", "dating"),
    "bumble": ("Bumble Premium", "dating"),
    "match.com": ("Match", "dating"),
    "hinge": ("Hinge Premium", "dating"),

    # Productivity / learning
    "masterclass": ("MasterClass", "learning"),
    "skillshare": ("Skillshare", "learning"),
    "coursera plus": ("Coursera Plus", "learning"),
    "duolingo plus": ("Duolingo Plus", "learning"),
    "babbel": ("Babbel", "learning"),
    "linkedin premium": ("LinkedIn Premium", "career"),

    # Subscription boxes
    "barkbox": ("BarkBox", "boxes"),
    "stitch fix": ("Stitch Fix", "boxes"),
    "ipsy": ("Ipsy", "boxes"),

    # Other
    "1password": ("1Password", "security"),
    "lastpass": ("LastPass", "security"),
    "nordvpn": ("NordVPN", "security"),
    "expressvpn": ("ExpressVPN", "security"),
}


@dataclass
class RawTransaction:
    """A single line item from the user's bank statement."""
    date: date
    description: str
    amount: Decimal  # positive for charges (debits)
    category: str = ""


@dataclass
class DetectedSubscription:
    canonical_name: str
    category: str
    matched_merchant_text: str
    monthly_amount: Decimal
    annual_amount: Decimal
    cadence: str  # "monthly", "annual", "quarterly", "weekly", "irregular"
    occurrences: int
    confidence: float  # 0.0 to 1.0
    first_seen: date
    last_seen: date
    flag_unused: bool = False
    flag_duplicate_category: bool = False
    transactions: List[RawTransaction] = field(default_factory=list)


@dataclass
class AuditResult:
    total_subscriptions: int
    total_monthly_spend: Decimal
    total_annual_spend: Decimal
    detected: List[DetectedSubscription]
    categories_breakdown: Dict[str, Decimal]
    flagged_duplicates: List[str]
    flagged_unused: List[str]
    insights: List[str]


# ─── CSV parsing ─────────────────────────────────────────────────────

def parse_bank_csv(csv_text: str) -> List[RawTransaction]:
    """
    Flexible bank statement CSV parser. Handles common US bank exports:
    Chase, BofA, Wells Fargo, Capital One, Citi, Amex, plus generic formats.
    """
    reader = csv.DictReader(io.StringIO(csv_text))
    txs: List[RawTransaction] = []

    for row in reader:
        r = {k.lower().strip(): (v or "").strip() for k, v in row.items() if k}

        # date
        date_str = (
            r.get("date") or r.get("transaction date") or r.get("posting date")
            or r.get("post date") or r.get("trans date") or ""
        )
        if not date_str:
            continue

        parsed_date = None
        for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%Y-%m-%dT%H:%M:%S",
                    "%d/%m/%Y", "%Y/%m/%d"):
            try:
                parsed_date = datetime.strptime(date_str, fmt).date()
                break
            except ValueError:
                continue
        if not parsed_date:
            continue

        # description
        description = (
            r.get("description") or r.get("merchant") or r.get("memo")
            or r.get("name") or r.get("payee") or r.get("details") or ""
        )
        if not description:
            continue

        # amount β€” handle multiple conventions
        amount = None
        amount_str = r.get("amount") or r.get("debit") or r.get("charges") or ""
        if amount_str:
            try:
                amt = Decimal(amount_str.replace(",", "").replace("$", "").strip())
                # Many bank CSVs use negative for debits; we want positive for charges
                amount = abs(amt) if amt < 0 else amt
                # If positive credits column exists, treat amount as charge
                credits_str = r.get("credit") or r.get("credits") or ""
                if credits_str and Decimal(credits_str.replace(",", "").replace("$", "") or "0") > 0:
                    continue  # this is a credit, not a charge
            except Exception:
                continue

        if amount is None or amount <= 0:
            continue

        category = r.get("category") or r.get("type") or ""

        txs.append(RawTransaction(
            date=parsed_date,
            description=description,
            amount=amount,
            category=category,
        ))

    return txs


# ─── Detection logic ─────────────────────────────────────────────────

def _normalize_merchant(description: str) -> str:
    """Strip noise from description for merchant matching."""
    s = description.lower()
    # Remove date stamps, transaction IDs, location codes
    s = re.sub(r"\d{2}/\d{2}", "", s)
    s = re.sub(r"\b\d{4,}\b", "", s)
    s = re.sub(r"#\w+", "", s)
    s = re.sub(r"\bpos\b|\bach\b|\bdr\b|\bcr\b|\bwww\.|\.com|\.net", "", s)
    s = re.sub(r"\s+", " ", s).strip()
    return s


def _match_known_merchant(description: str) -> Optional[tuple]:
    """Return (canonical_name, category) if description matches a known merchant."""
    norm = _normalize_merchant(description)
    for keyword, (name, cat) in KNOWN_MERCHANTS.items():
        if keyword in norm:
            return name, cat
    return None


def _detect_cadence(dates: List[date]) -> tuple[str, float]:
    """Given dates of recurring charges, return (cadence_label, confidence)."""
    if len(dates) < 2:
        return "irregular", 0.3

    sorted_dates = sorted(dates)
    intervals = [(sorted_dates[i+1] - sorted_dates[i]).days for i in range(len(sorted_dates) - 1)]
    avg = sum(intervals) / len(intervals)

    # variance check β€” low variance = high confidence
    variance = sum((i - avg) ** 2 for i in intervals) / len(intervals)
    std_dev = variance ** 0.5

    if 25 <= avg <= 35:
        cadence = "monthly"
    elif 80 <= avg <= 100:
        cadence = "quarterly"
    elif 350 <= avg <= 380:
        cadence = "annual"
    elif 6 <= avg <= 9:
        cadence = "weekly"
    elif 13 <= avg <= 17:
        cadence = "biweekly"
    else:
        cadence = "irregular"

    # Confidence: how regular is the cadence
    if std_dev < 3:
        confidence = 0.95
    elif std_dev < 7:
        confidence = 0.85
    elif std_dev < 15:
        confidence = 0.65
    else:
        confidence = 0.40

    return cadence, confidence


def _normalize_to_monthly(amount: Decimal, cadence: str) -> Decimal:
    """Convert any cadence to monthly equivalent."""
    if cadence == "monthly":
        return amount
    if cadence == "annual":
        return (amount / 12).quantize(Decimal("0.01"))
    if cadence == "quarterly":
        return (amount / 3).quantize(Decimal("0.01"))
    if cadence == "weekly":
        return (amount * Decimal("4.33")).quantize(Decimal("0.01"))
    if cadence == "biweekly":
        return (amount * Decimal("2.17")).quantize(Decimal("0.01"))
    return amount


def detect_subscriptions(transactions: List[RawTransaction]) -> AuditResult:
    """
    Run full subscription detection on a list of bank transactions.
    Returns AuditResult with all detected subscriptions, totals, and insights.
    """
    # Step 1: Group transactions by likely merchant
    by_merchant: Dict[str, List[RawTransaction]] = defaultdict(list)

    for tx in transactions:
        known = _match_known_merchant(tx.description)
        if known:
            merchant_key = known[0]
        else:
            # Group by normalized description (rough)
            merchant_key = _normalize_merchant(tx.description)[:30]
        by_merchant[merchant_key].append(tx)

    # Step 2: For each merchant group with 2+ charges, evaluate as subscription candidate
    detected: List[DetectedSubscription] = []

    for merchant, txs in by_merchant.items():
        if len(txs) < 2:
            continue

        amounts = [tx.amount for tx in txs]
        # Check amount consistency (allow Β±5% variance for annual price increases)
        avg_amount = sum(amounts, Decimal("0")) / len(amounts)
        max_dev = max(abs(a - avg_amount) for a in amounts)
        if avg_amount > 0 and max_dev / avg_amount > Decimal("0.20"):
            # Too much variance β€” probably not a subscription (allow up to 20% for annual price increases)
            continue

        dates = [tx.date for tx in txs]
        cadence, confidence = _detect_cadence(dates)

        # Boost confidence if known merchant
        known = _match_known_merchant(txs[0].description)
        if known:
            confidence = min(1.0, confidence + 0.10)
            canonical, category = known
        else:
            # Generic β€” only count high-confidence regular cadences
            if confidence < 0.65:
                continue
            canonical = merchant.title()
            category = "other"

        avg_amount_dec = avg_amount.quantize(Decimal("0.01"))
        monthly = _normalize_to_monthly(avg_amount_dec, cadence)
        annual = (monthly * 12).quantize(Decimal("0.01"))

        # Unused detection: if last charge >60 days ago, flag as possibly forgotten
        last_seen = max(dates)
        flag_unused = (date.today() - last_seen).days > 60 if cadence in ("monthly", "annual") else False

        detected.append(DetectedSubscription(
            canonical_name=canonical,
            category=category,
            matched_merchant_text=txs[0].description[:50],
            monthly_amount=monthly,
            annual_amount=annual,
            cadence=cadence,
            occurrences=len(txs),
            confidence=confidence,
            first_seen=min(dates),
            last_seen=last_seen,
            flag_unused=flag_unused,
            transactions=txs,
        ))

    # Step 3: Flag duplicates within categories (e.g., 3 streaming services)
    by_category: Dict[str, List[DetectedSubscription]] = defaultdict(list)
    for s in detected:
        by_category[s.category].append(s)

    flagged_duplicates = []
    for cat, subs in by_category.items():
        if len(subs) >= 3 and cat in ("streaming", "music", "ai", "news", "fitness"):
            names = ", ".join(s.canonical_name for s in subs)
            flagged_duplicates.append(f"{cat}: {names}")
            for s in subs:
                s.flag_duplicate_category = True

    # Aggregate totals
    total_monthly = sum((s.monthly_amount for s in detected), Decimal("0"))
    total_annual = sum((s.annual_amount for s in detected), Decimal("0"))

    categories_breakdown = {
        cat: sum((s.monthly_amount for s in subs), Decimal("0"))
        for cat, subs in by_category.items()
    }

    flagged_unused = [s.canonical_name for s in detected if s.flag_unused]

    # Generate insights
    insights = []
    if total_monthly > 0:
        if total_annual > 1000:
            insights.append(f"You're spending **${total_annual:,.0f}/year** on subscriptions β€” that's ${total_monthly:,.0f}/month.")
        avg_household = Decimal("219")  # ~2026 US average
        if total_monthly > avg_household:
            diff = total_monthly - avg_household
            insights.append(f"That's **${diff:,.0f}/month above** the US household average of ${avg_household}/month.")

    if flagged_duplicates:
        for fd in flagged_duplicates:
            insights.append(f"⚠️ Multiple services in same category β€” possible overlap: {fd}")

    if flagged_unused:
        insights.append(f"⚠️ {len(flagged_unused)} subscription(s) haven't charged in 60+ days but may auto-renew: {', '.join(flagged_unused[:5])}")

    # Top spend
    if detected:
        top = max(detected, key=lambda s: s.monthly_amount)
        insights.append(f"Highest spend: **{top.canonical_name}** at ${top.monthly_amount}/month (${top.annual_amount:,.0f}/year).")

    return AuditResult(
        total_subscriptions=len(detected),
        total_monthly_spend=total_monthly.quantize(Decimal("0.01")),
        total_annual_spend=total_annual.quantize(Decimal("0.01")),
        detected=sorted(detected, key=lambda s: -s.monthly_amount),
        categories_breakdown=categories_breakdown,
        flagged_duplicates=flagged_duplicates,
        flagged_unused=flagged_unused,
        insights=insights,
    )