from pathlib import Path

from openpyxl import load_workbook

from app.processor import process_import


def test_success_import(fixtures: dict[str, Path], tmp_path: Path) -> None:
    result = process_import(fixtures["table_a_success"], fixtures["template_b"], tmp_path)
    assert result.success, result.message
    assert result.stats["customers_source"] == 10
    assert result.stats["customers_imported"] == 10
    assert result.stats["addresses_complete"] == 10
    assert result.stats["plates_present"] == 10
    assert result.stats["vins_present"] == 10
    assert result.stats["salutations_complete"] == 10
    assert result.output_path

    wb = load_workbook(result.output_path)
    assert "Importprüfung" in wb.sheetnames
    data = wb[wb.sheetnames[0]]
    names: list[str] = []
    streets: list[str] = []
    salutations: list[str] = []
    for row in data.iter_rows(min_row=2, values_only=True):
        names.append(str(row[4] or ""))
        streets.append(str(row[7] or ""))
        salutations.append(str(row[11] or ""))
    assert "Kundin" not in names
    assert "Beispiel" not in names
    assert any("Russeer Weg 9" in s for s in streets)
    assert any("Wellseedamm" in s for s in streets)
    assert any("Fördestraße 21" in s or "Fordestrasse 21" in s for s in streets)
    assert "Sehr geehrter Herr Dr. Weber" in salutations
    assert "Sehr geehrte Frau Schmidt" in salutations
    assert "Sehr geehrte Frau Klein" in salutations
    assert "Sehr geehrte Damen und Herren" in salutations
    wb.close()


def test_missing_address_fails(fixtures: dict[str, Path], tmp_path: Path) -> None:
    result = process_import(fixtures["table_a_missing_address"], fixtures["template_b"], tmp_path)
    assert not result.success
    assert "IMPORT FEHLGESCHLAGEN" in result.message
    assert result.output_path is None
    assert any(
        "Straße fehlt" in (issue.get("reasons") or [])
        or "Ohne" in (issue.get("name") or "")
        or "Adresse" in (issue.get("name") or "")
        or "Unbekannte" in (issue.get("name") or "")
        for issue in result.issues
    )


def test_conflict_fails(fixtures: dict[str, Path], tmp_path: Path) -> None:
    result = process_import(fixtures["table_a_conflict"], fixtures["template_b"], tmp_path)
    assert not result.success
    assert result.output_path is None
    assert result.stats.get("conflicts", 0) >= 1
