from __future__ import annotations

import io
from typing import Any

import openpyxl


def workbook_bytes_to_contact_rows(file_bytes: bytes) -> dict[str, Any]:
    """
    Reads first sheet; finds name + phone columns like parseCsvContent header rules.
    """
    try:
        wb = openpyxl.load_workbook(io.BytesIO(file_bytes), read_only=True, data_only=True)
        ws = wb[wb.sheetnames[0]]
        rows_iter = ws.iter_rows(values_only=True)
        try:
            header_row = next(rows_iter)
        except StopIteration:
            return {"success": False, "error": "Excel file is empty"}

        headers = [str(c).strip() if c is not None else "" for c in header_row]
        name_column_index = -1
        contact_column_index = -1
        for i, header in enumerate(headers):
            normalized = header.lower().strip()
            if any(x in normalized for x in ("name", "fullname", "full_name", "customer_name")):
                name_column_index = i
            if any(
                x in normalized
                for x in (
                    "contact",
                    "phone",
                    "mobile",
                    "number",
                    "phone_number",
                    "mobile_number",
                )
            ):
                contact_column_index = i

        if name_column_index == -1 or contact_column_index == -1:
            return {
                "success": False,
                "error": "Could not find name and contact columns. Found: " + ", ".join(headers),
            }

        contacts: list[dict[str, str]] = []
        for row in rows_iter:
            if row is None:
                continue
            lst = list(row)
            name = str(lst[name_column_index]).strip() if name_column_index < len(lst) and lst[name_column_index] is not None else ""
            contact = (
                str(lst[contact_column_index]).strip()
                if contact_column_index < len(lst) and lst[contact_column_index] is not None
                else ""
            )
            if name or contact:
                contacts.append({"name": name, "contact": contact})

        wb.close()

        if not contacts:
            return {"success": False, "error": "No valid contact data found"}

        return {
            "success": True,
            "message": f"Successfully parsed {len(contacts)} contacts",
            "total_count": len(contacts),
            "contacts": contacts,
            "columns_found": headers,
        }
    except Exception as e:  # noqa: BLE001
        return {"success": False, "error": f"Error parsing Excel: {e}"}
