import pdfplumber
from typing import List, Dict, Any, BinaryIO
from datetime import datetime
from .base_parser import BaseBankStatementParser
import re

class TCBPdfParser(BaseBankStatementParser):
    """
    Parser for Techcombank PDF statements.
    """
    def __init__(self, password: str = None):
        self.password = password

    def _parse_amount(self, amt_str: str) -> float:
        if not amt_str:
            return 0.0
        # Remove commas and convert to float
        clean_str = amt_str.replace(",", "").strip()
        try:
            return float(clean_str)
        except ValueError:
            return 0.0

    def parse(self, file_content: BinaryIO, filename: str) -> List[Dict[str, Any]]:
        transactions = []
        with pdfplumber.open(file_content, password=self.password) as pdf:
            for page in pdf.pages:
                tables = page.extract_tables()
                if not tables:
                    continue
                for table in tables:
                    for row in table:
                        if not row or len(row) < 10:
                            continue
                        
                        date_str = row[0]
                        if not date_str or not re.match(r'\d{2}/\d{2}/\d{4}', date_str):
                            continue
                            
                        try:
                            tx_date = datetime.strptime(date_str.strip()[:10], "%d/%m/%Y")
                            
                            desc = (row[3] or "").replace("\n", " ")
                            ref = (row[4] or "").replace("\n", "")
                            
                            debit = self._parse_amount(row[5])
                            credit = self._parse_amount(row[6])
                            balance = self._parse_amount(row[9])
                            
                            tx = {
                                "transaction_date": tx_date,
                                "transaction_reference": ref,
                                "description": desc,
                                "debit_amount_vnd": debit,
                                "credit_amount_vnd": credit,
                                "running_balance_vnd": balance
                            }
                            transactions.append(tx)
                        except Exception as e:
                            # Skip row on error
                            pass
        return transactions
