import csv
from datetime import date, datetime
from decimal import Decimal
import hashlib
import io
import re
import openpyxl


def make_line_fingerprint(
    txn_date: date, reference_no: str, cheque_no: str, description: str, debit: Decimal, credit: Decimal, row_idx: int
) -> str:
    """Create deterministic fingerprint to block duplicate statement re-imports."""
    raw = f"{txn_date.isoformat()}|{reference_no.strip()}|{cheque_no.strip()}|{description.strip()}|{debit:.2f}|{credit:.2f}"
    if not reference_no.strip() and not cheque_no.strip():
        raw += f"|seq:{row_idx}"
    return hashlib.sha256(raw.encode("utf-8")).hexdigest()


def _parse_date(val) -> date:
    if isinstance(val, datetime):
        return val.date()
    if isinstance(val, date):
        return val
    s = str(val).strip()
    for fmt in ("%Y-%m-%d", "%d/%m/%Y", "%m/%d/%Y", "%Y%m%d"):
        try:
            return datetime.strptime(s[:10], fmt).date()
        except ValueError:
            continue
    return date.fromisoformat(s[:10])


def _dec(val) -> Decimal:
    if val is None or str(val).strip() == "":
        return Decimal("0.00")
    s = str(val).replace(",", "").strip()
    return Decimal(s)


def parse_csv_statement(content_bytes: bytes, mapping: dict | None = None) -> list[dict]:
    text = content_bytes.decode("utf-8-sig")
    reader = csv.DictReader(io.StringIO(text))
    m = mapping or {}
    d_col = (m.get("date_col") or "date").lower()
    r_col = (m.get("ref_col") or "reference").lower()
    c_col = (m.get("cheque_col") or "cheque_no").lower()
    desc_col = (m.get("desc_col") or "description").lower()
    dr_col = (m.get("debit_col") or "debit").lower()
    cr_col = (m.get("credit_col") or "credit").lower()
    bal_col = (m.get("balance_col") or "balance").lower()

    rows = []
    for idx, row in enumerate(reader, start=1):
        norm = {str(k).strip().lower(): v for k, v in row.items() if k is not None}
        txn_d = _parse_date(norm.get(d_col) or norm.get("date") or norm.get("txn_date") or norm.get("value_date"))
        debit = _dec(norm.get(dr_col) or norm.get("debit") or norm.get("withdrawal") or 0)
        credit = _dec(norm.get(cr_col) or norm.get("credit") or norm.get("deposit") or 0)
        ref = str(norm.get(r_col) or norm.get("reference") or norm.get("reference_no") or "").strip()
        chq = str(norm.get(c_col) or norm.get("cheque_no") or norm.get("cheque") or "").strip()
        desc = str(norm.get(desc_col) or norm.get("description") or norm.get("narration") or norm.get("particulars") or "").strip()
        bal = _dec(norm[bal_col]) if norm.get(bal_col) not in (None, "") else (_dec(norm["balance"]) if norm.get("balance") not in (None, "") else None)
        rows.append(
            {
                "txn_date": txn_d,
                "reference_no": ref,
                "cheque_no": chq,
                "description": desc,
                "debit": debit,
                "credit": credit,
                "balance": bal,
                "fingerprint": make_line_fingerprint(txn_d, ref, chq, desc, debit, credit, idx),
            }
        )
    return rows


def parse_xlsx_statement(content_bytes: bytes, mapping: dict | None = None) -> list[dict]:
    wb = openpyxl.load_workbook(io.BytesIO(content_bytes), read_only=True, data_only=True)
    ws = wb.active
    raw_rows = list(ws.iter_rows(values_only=True))
    if not raw_rows:
        return []
    m = mapping or {}
    d_col = (m.get("date_col") or "date").lower()
    r_col = (m.get("ref_col") or "reference").lower()
    c_col = (m.get("cheque_col") or "cheque_no").lower()
    desc_col = (m.get("desc_col") or "description").lower()
    dr_col = (m.get("debit_col") or "debit").lower()
    cr_col = (m.get("credit_col") or "credit").lower()
    bal_col = (m.get("balance_col") or "balance").lower()

    headers = [str(h or "").strip().lower() for h in raw_rows[0]]
    rows = []
    for idx, vals in enumerate(raw_rows[1:], start=1):
        if not any(vals):
            continue
        norm = dict(zip(headers, vals))
        txn_d = _parse_date(norm.get(d_col) or norm.get("date") or norm.get("txn_date"))
        debit = _dec(norm.get(dr_col) or norm.get("debit") or norm.get("withdrawal") or 0)
        credit = _dec(norm.get(cr_col) or norm.get("credit") or norm.get("deposit") or 0)
        ref = str(norm.get(r_col) or norm.get("reference") or norm.get("reference_no") or "").strip()
        chq = str(norm.get(c_col) or norm.get("cheque_no") or norm.get("cheque") or "").strip()
        desc = str(norm.get(desc_col) or norm.get("description") or norm.get("narration") or "").strip()
        bal = _dec(norm[bal_col]) if norm.get(bal_col) not in (None, "") else (_dec(norm["balance"]) if norm.get("balance") not in (None, "") else None)
        rows.append(
            {
                "txn_date": txn_d,
                "reference_no": ref,
                "cheque_no": chq,
                "description": desc,
                "debit": debit,
                "credit": credit,
                "balance": bal,
                "fingerprint": make_line_fingerprint(txn_d, ref, chq, desc, debit, credit, idx),
            }
        )
    return rows


def parse_ofx_statement(content_bytes: bytes) -> list[dict]:
    text = content_bytes.decode("utf-8", errors="ignore")
    blocks = re.findall(r"<STMTTRN>(.*?)</STMTTRN>", text, flags=re.DOTALL | re.IGNORECASE)
    rows = []
    for idx, block in enumerate(blocks, start=1):
        def tag(name: str) -> str:
            m = re.search(rf"<{name}>([^<\r\n]+)", block, flags=re.IGNORECASE)
            return m.group(1).strip() if m else ""

        dt_raw = tag("DTPOSTED")[:8]
        txn_d = _parse_date(dt_raw)
        amt = _dec(tag("TRNAMT"))
        credit = amt if amt > 0 else Decimal("0.00")
        debit = abs(amt) if amt < 0 else Decimal("0.00")
        ref = tag("FITID")
        chq = tag("CHECKNUM")
        desc = tag("NAME") or tag("MEMO")
        rows.append(
            {
                "txn_date": txn_d,
                "reference_no": ref,
                "cheque_no": chq,
                "description": desc,
                "debit": debit,
                "credit": credit,
                "balance": None,
                "fingerprint": make_line_fingerprint(txn_d, ref, chq, desc, debit, credit, idx),
            }
        )
    return rows


def parse_qif_statement(content_bytes: bytes) -> list[dict]:
    text = content_bytes.decode("utf-8", errors="ignore")
    records = text.split("^")
    rows = []
    for idx, rec in enumerate(records, start=1):
        lines = [ln.strip() for ln in rec.splitlines() if ln.strip() and not ln.strip().startswith("!")]
        if not lines:
            continue
        d_raw, amt_raw, ref, desc = "", "0", "", ""
        for ln in lines:
            tag, val = ln[0], ln[1:].strip()
            if tag == "D":
                d_raw = val
            elif tag == "T":
                amt_raw = val
            elif tag == "N":
                ref = val
            elif tag in ("P", "M"):
                desc = f"{desc} {val}".strip()
        if not d_raw:
            continue
        txn_d = _parse_date(d_raw)
        amt = _dec(amt_raw)
        credit = amt if amt > 0 else Decimal("0.00")
        debit = abs(amt) if amt < 0 else Decimal("0.00")
        chq = ref if ref.isdigit() else ""
        rows.append(
            {
                "txn_date": txn_d,
                "reference_no": ref,
                "cheque_no": chq,
                "description": desc,
                "debit": debit,
                "credit": credit,
                "balance": None,
                "fingerprint": make_line_fingerprint(txn_d, ref, chq, desc, debit, credit, idx),
            }
        )
    return rows


def parse_mt940_statement(content_bytes: bytes) -> list[dict]:
    text = content_bytes.decode("utf-8", errors="ignore")
    lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
    rows = []
    current = None
    idx = 0
    for ln in lines:
        if ln.startswith(":61:"):
            if current:
                rows.append(current)
            idx += 1
            body = ln[4:].strip()
            m = re.match(r"(\d{6})(?:\d{4})?(C|D|RC|RD)([0-9,\.]+)[A-Z]{4}(.*)", body)
            if not m:
                current = None
                continue
            yymmdd, dc, amt_str, ref = m.groups()
            txn_d = datetime.strptime("20" + yymmdd, "%Y%m%d").date()
            amt = _dec(amt_str.replace(",", "."))
            credit = amt if dc in ("C", "RC") else Decimal("0.00")
            debit = amt if dc in ("D", "RD") else Decimal("0.00")
            ref_clean = ref.strip()[:64]
            current = {
                "txn_date": txn_d,
                "reference_no": ref_clean,
                "cheque_no": "",
                "description": ref_clean,
                "debit": debit,
                "credit": credit,
                "balance": None,
                "fingerprint": "",
            }
        elif ln.startswith(":86:") and current:
            current["description"] = ln[4:].strip()[:255]
    if current:
        rows.append(current)
    for idx, r in enumerate(rows, start=1):
        r["fingerprint"] = make_line_fingerprint(
            r["txn_date"], r["reference_no"], r["cheque_no"], r["description"], r["debit"], r["credit"], idx
        )
    return rows


def parse_statement_bytes(file_format: str, content_bytes: bytes, mapping: dict | None = None) -> list[dict]:
    fmt = file_format.upper()
    if fmt in ("XLSX", "XLS"):
        return parse_xlsx_statement(content_bytes, mapping=mapping)
    if fmt == "OFX":
        return parse_ofx_statement(content_bytes)
    if fmt == "QIF":
        return parse_qif_statement(content_bytes)
    if fmt == "MT940":
        return parse_mt940_statement(content_bytes)
    return parse_csv_statement(content_bytes, mapping=mapping)

