"""
Recipe: extract unmatched rows (missing SFDC IDs) and propose SOQL hints.
"""

from __future__ import annotations

import csv
from dataclasses import dataclass
from pathlib import Path
from typing import List

from g_gremlin.normalize import normalize_name


@dataclass
class ResolveUnmatchedResult:
    unmatched_rows: int
    rows_written: int


def resolve_unmatched(
    csv_path: Path,
    id_column: str,
    name_column: str,
    output_path: Path,
    object_name: str = "Account",
) -> ResolveUnmatchedResult:
    """
    Extract rows missing IDs and generate suggested SOQL lookups for manual resolution.
    """
    with csv_path.open("r", newline="", encoding="utf-8-sig") as handle:
        reader = csv.DictReader(handle)
        if reader.fieldnames is None:
            raise ValueError(f"CSV {csv_path} is missing a header row.")
        rows = list(reader)

    unmatched: List[dict] = []
    for idx, row in enumerate(rows, start=2):  # header is row 1
        raw_id = (row.get(id_column) or "").strip()
        if raw_id:
            continue
        raw_name = (row.get(name_column) or "").strip()
        norm = normalize_name(raw_name) if raw_name else ""
        suggested = _build_soql(norm, object_name)
        unmatched.append(
            {
                "Row_Number": str(idx),
                name_column: raw_name,
                "Normalized_Name": norm,
                "Suggested_SOQL": suggested,
            }
        )

    output_headers = ["Row_Number", name_column, "Normalized_Name", "Suggested_SOQL"]
    output_path.parent.mkdir(parents=True, exist_ok=True)
    with output_path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=output_headers)
        writer.writeheader()
        for row in unmatched:
            writer.writerow(row)

    return ResolveUnmatchedResult(unmatched_rows=len(unmatched), rows_written=len(unmatched))


def _build_soql(normalized_name: str, object_name: str) -> str:
    if not normalized_name:
        return f"SELECT Id, Name FROM {object_name} WHERE Name LIKE '%<fill_me>%'"  # prompt for manual fill
    pattern = "%" + "%".join(normalized_name.split()) + "%"
    safe_pattern = pattern.replace("'", "\\'")
    return f"SELECT Id, Name FROM {object_name} WHERE Name LIKE '{safe_pattern}'"
