from datetime import datetime
from logging_config import get_logger

logger = get_logger(__name__)

class Processor:
    def __init__(self, config, repo, api):
        self.config = config
        self.repo = repo
        self.api = api

    def process(self):
        rows = self.repo.get_pending_rrns_today()
        logger.info("Pending transactions count: %s", len(rows))

        for r in rows:
            bank_code = self.config.BANK_CODE_MAPPING.get(r["DCCB_CODE"])
            if not bank_code:
                logger.info(
                    "Skipping TXN_NO=%s due to missing bank mapping for DCCB=%s",
                    r["TXN_NO"],
                    r["DCCB_CODE"]
                )
                continue

            payload = {
                "bankCode": bank_code,
                "rrn": r["RRN_TWO"],
                "branchCode": r["BR_CODE"],
                "itemType": 0,
                "queueType": "02",
                "reterieveTop": "20"
            }

            logger.info(
                "Calling fetchAllQueue API for TXN_NO=%s, RRN=%s with payload=%s",
                r["TXN_NO"],
                r["RRN_TWO"],
                payload
            )

            response = self.api.fetch(payload)

            #  Log FULL API response
            logger.info(
                "API response received for TXN_NO=%s, RRN_TWO=%s : %s",
                r["TXN_NO"],
                r["RRN_TWO"],
                response
            )

            items = response.get("response", {}).get("VwQueueItems", [])

            if not items:
                logger.info(
                    "No VwQueueItems found for TXN_NO=%s, RRN_TWO=%s",
                    r["TXN_NO"],
                    r["RRN_TWO"]
                )
                continue

            status = items[0].get("status")
            logger.info(
                "Queue item status for TXN_NO=%s, RRN_TWO=%s is %s",
                r["TXN_NO"],
                r["RRN_two"],
                status
            )

            if status != "PROCESSED":
                logger.info(
                    "Skipping TXN_NO=%s as status is not PROCESSED",
                    r["TXN_NO"]
                )
                continue

            item = items[0]
           
            sender_ifsc = item.get("sender_ifsc")


            log_data = {
                "bankcode": bank_code,
                "jrnl_id": item["journalId"],
                "ref_no": item.get("remarks"),
                "tran_date": datetime.now().strftime("%d%m%Y"),
                "txn_amt": r["TXN_AMT"],
                "recv_ac": r["DEST_AC_NO"],
                "send_ac": r["SRC_AC_NO"],
                "ifsc": r["IFSC_CODE"],
                "sender_ifsc": sender_ifsc,
                "sender_name": r["REMITTER_NAME"],
                "receiver_name": r["BENEFICIARY_NAME"],
                "beneficiary_address": r["BENEFICIARY_ADD"],
                "sender_info": item["sendeReceiverInfo"]
            }

            #  Log DB payload BEFORE insert
            logger.info(
                "Inserting outward_neft_api_log for TXN_NO=%s with data=%s",
                r["TXN_NO"],
                log_data
            )

            #  Insert into outward_neft_api_log
            self.repo.insert_outward_log(log_data)

            #  Update MARK_TYPE
            self.repo.mark_processed(r["TXN_NO"])

            logger.info(
                "SUCCESS: Inserted outward log and updated MARK_TYPE=Y for TXN_NO=%s, RRN_TWO=%s",
                r["TXN_NO"],
                r["RRN_TWO"]
            )
