from __future__ import annotations

import re

PERIOD_RE = re.compile(r"Statement Period:\s*(\d{4}-\d{2}-\d{2})\s*to\s*(\d{4}-\d{2}-\d{2})")
ACCOUNT_RE = re.compile(r"Account Number:\s*([0-9*Xx-]+)")
ROW_RE = re.compile(
    r"^(\d{4}-\d{2}-\d{2})\s+(.+?)\s+(-?\d+[\d,]*\.\d{2})\s+(-?\d+[\d,]*\.\d{2})$",
    re.MULTILINE,
)


def detect(full_text: str) -> float:
    text = full_text or ""
    score = 0.0
    if "Example Bank" in text:
        score += 0.5
    if "Statement Period:" in text:
        score += 0.3
    if "Account Number:" in text:
        score += 0.2
    return min(score, 1.0)


def parse(full_text: str, source_file: str) -> dict:
    period = PERIOD_RE.search(full_text)
    start = period.group(1) if period else ""
    end = period.group(2) if period else ""

    acct = ACCOUNT_RE.search(full_text)
    account_number = acct.group(1) if acct else ""

    txs = []
    for m in ROW_RE.finditer(full_text):
        post_date, description, amount_s, balance_s = m.groups()
        amount = float(amount_s.replace(",", ""))
        balance = float(balance_s.replace(",", ""))
        txs.append(
            {
                "post_date": post_date,
                "description": description,
                "amount": amount,
                "balance": balance,
                "row_confidence": 0.9,
                "review_reason": "",
            }
        )

    return {
        "statement_start": start,
        "statement_end": end,
        "account_number": account_number,
        "transactions": txs,
        "warnings": [],
    }
