"""Tests for CSV import skill behavior."""

from __future__ import annotations

import tempfile
import unittest
from pathlib import Path

from kiessclaw.skills.csv_import import import_contacts_csv


class CsvImportTest(unittest.TestCase):
    """Validate robust CSV import and filtering behavior."""

    def test_basic_import_sample_csv(self) -> None:
        """Sample leads CSV should import exactly three contacts."""
        result = import_contacts_csv("examples/sample_leads.csv")
        self.assertEqual(3, result.contacts_added)
        self.assertEqual(0, result.contacts_skipped)
        self.assertFalse(result.errors)

    def test_alias_autodetect_maps_email_address(self) -> None:
        """Alias detection should map common alternate headers automatically."""
        with tempfile.TemporaryDirectory() as tempdir:
            csv_path = Path(tempdir) / "aliases.csv"
            csv_path.write_text(
                "Email Address,First Name,Last Name,Org,Role,Website\n"
                "person@example.com,Ada,Lovelace,Analytical,Engineer,example.com\n",
                encoding="utf-8",
            )
            result = import_contacts_csv(str(csv_path))
            self.assertEqual(1, result.contacts_added)
            self.assertEqual("person@example.com", result.contacts[0].email)

    def test_deduplicate_on_reimport(self) -> None:
        """Passing previous emails should skip duplicates on second import."""
        first = import_contacts_csv("examples/sample_leads.csv", deduplicate=True)
        existing = {contact.email for contact in first.contacts}
        second = import_contacts_csv("examples/sample_leads.csv", deduplicate=True, existing_emails=existing)
        self.assertEqual(0, second.contacts_added)
        self.assertEqual(3, second.contacts_skipped)

    def test_icp_score_min_filter(self) -> None:
        """Very high ICP threshold should produce no qualified contacts."""
        result = import_contacts_csv("examples/sample_leads.csv", icp_score_min=100)
        self.assertEqual(0, len(result.qualified))

    def test_malformed_csv_returns_errors(self) -> None:
        """CSV missing required email column should return structured errors."""
        with tempfile.TemporaryDirectory() as tempdir:
            csv_path = Path(tempdir) / "bad.csv"
            csv_path.write_text("first_name,last_name\nAlex,Rivera\n", encoding="utf-8")
            result = import_contacts_csv(str(csv_path))
            self.assertTrue(result.errors)
            self.assertIn("Missing required email column", result.errors[0])

    def test_column_map_override(self) -> None:
        """Explicit mapping should override header auto-detection."""
        with tempfile.TemporaryDirectory() as tempdir:
            csv_path = Path(tempdir) / "mapped.csv"
            csv_path.write_text(
                "EmailCol,Given,Family,OrgName,Job,Site\n"
                "mapped@example.com,Map,User,MapCo,CTO,mapco.com\n",
                encoding="utf-8",
            )
            result = import_contacts_csv(
                str(csv_path),
                column_map={
                    "email": "EmailCol",
                    "first_name": "Given",
                    "last_name": "Family",
                    "company": "OrgName",
                    "title": "Job",
                    "domain": "Site",
                },
            )
            self.assertEqual(1, result.contacts_added)
            self.assertEqual("mapped@example.com", result.contacts[0].email)


if __name__ == "__main__":
    unittest.main()
