from __future__ import annotations
import re, pandas as pd
from pathlib import Path
from .base import *
from .common import DATE_TOKEN_PATTERN, date_iso, find, find_date_tokens

class AxisParser(BaseParser):
    bank_name='Axis Bank'; parser_name='AxisParser'
    @classmethod
    def detect(cls,text): return 0.98 if 'SMART STATEMENT REPORT' in text.upper() and 'UTIB' in text.upper() else 0
    def parse(self,path,text=None):
        text=text or extract_text(path); meta=StatementMeta(bank_name=self.bank_name,source_file=Path(path).name,parser_name=self.parser_name,confidence='High')
        # name is first meaningful line after report title
        m=re.search(r'Smart Statement Report\s*\n\s*([^\n]+)',text,re.I); meta.customer_name=norm(m.group(1)) if m else ''
        meta.account_number=find(r'Statement of Account No\s*-\s*([^\s]*)',text)
        meta.ifsc=find(r'IFSC:\s*([A-Z0-9]+)',text)
        m=re.search(rf'for period\s*\(({DATE_TOKEN_PATTERN})\s+to\s+({DATE_TOKEN_PATTERN})\)', text, re.I)
        if m: meta.period_from=date_iso(m.group(1)); meta.period_to=date_iso(m.group(2))
        meta.opening_balance=amount(find(r'Opening Balance:\s*INR\s*([\d,]+\.\d{2})',text))
        pat=re.compile(rf'^\s*(\d+)\s+({DATE_TOKEN_PATTERN})\s+({DATE_TOKEN_PATTERN})\s+(.*)$', re.I)
        rows=[]; cur=None; page=1
        for line in text.splitlines():
            if '\f' in line: page+=line.count('\f')
            m=pat.match(line)
            if m:
                if cur: rows.append(cur)
                cur={'transaction_date':m.group(2),'value_date':m.group(3),'body':m.group(4),'source_page':page}
            elif cur and line.strip() and not re.match(r'^(S\. No\.|Smart Statement|Page )',line.strip(),re.I): cur['body']+=' '+line.strip()
        if cur: rows.append(cur)
        out=[]
        for r in rows:
            b=norm(r['body']); ma=re.search(r'INR\s*([\d,]+\.\d{2})\s+(CR|DR)\s+INR\s*([\d,]+\.\d{2})',b,re.I)
            if not ma: continue
            txn=amount(ma.group(1)); typ=ma.group(2).upper(); bal=amount(ma.group(3)); narr=b[:ma.start()].strip(); ref=''
            z=re.search(r'([A-Z0-9/-]{8,})',narr); ref=z.group(1) if z else ''
            out.append({**r,'narration':narr,'reference_no':ref,'debit':txn if typ=='DR' else None,'credit':txn if typ=='CR' else None,'balance':bal})
        return meta,finalize(pd.DataFrame(out),meta)
