import json
import os
import re
from typing import Any, Dict, List

from openpyxl import load_workbook

from backend.pashub_fetcher.pashub_to_ara_trigger_request import (
    PashubToAraTriggerRequest,
)
from backend.pashub_fetcher.handler.handler import handler


if __name__ == "__main__":
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    filepath: str = os.path.join(
        BASE_DIR,
        "pashub_fetcher",
        "The_Guinness_Partnership_AtkinsR_alis_Coordination_Design_Board_1774881298.xlsx",
    )

    wb = load_workbook(filepath, data_only=True)
    ws = wb["filtered_2"]

    HEADER_ROW = 3

    headers: Dict[str, int] = {}
    for col in range(1, ws.max_column + 1):
        value = str(ws.cell(row=HEADER_ROW, column=col).value)
        if value:
            headers[value.strip()] = col

    name_col = headers["Name"]
    link_col = headers["PasHub Link"]
    hubspot_deal_id_col = headers["HubSpot ID"]

    trigger_requests: List[PashubToAraTriggerRequest] = []

    for row in range(HEADER_ROW + 1, ws.max_row + 1):
        name = ws.cell(row=row, column=name_col).value
        link = ws.cell(row=row, column=link_col).value
        hubspot_deal_id = ws.cell(row=row, column=hubspot_deal_id_col).value

        if not name or not link or not hubspot_deal_id:
            continue

        match = re.search(r"/jobs/([0-9a-fA-F\-]+)/", str(link))
        if not match:
            continue

        trigger_requests.append(
            PashubToAraTriggerRequest(
                pashub_link=str(link), hubspot_deal_id=str(hubspot_deal_id)
            )
        )

    # ---- Build fake SQS event ----
    event: Dict[str, Any] = {
        "Records": [{"body": json.dumps(req.model_dump())} for req in trigger_requests]
    }

    context = None
    handler(event, context)
