import json
import sqlite3
from datetime import datetime
from pathlib import Path

from modules.core import storage_paths

CLIENT_STATUS_OPTIONS = [
    {"value": "new", "label": "Nowy"},
    {"value": "contacted", "label": "Po kontakcie"},
    {"value": "interested", "label": "Zainteresowany"},
    {"value": "offer_sent", "label": "Wysłano oferty"},
    {"value": "meeting_planned", "label": "Umówione spotkanie"},
    {"value": "negotiation", "label": "Negocjacje"},
    {"value": "won", "label": "Klient pozyskany"},
    {"value": "lost", "label": "Utracony"},
    {"value": "inactive", "label": "Nieaktywny"},
]

CLIENT_TYPE_OPTIONS = [
    {"value": "buyer", "label": "Kupujący"},
    {"value": "investor", "label": "Inwestor"},
    {"value": "tenant", "label": "Najemca"},
    {"value": "seller", "label": "Sprzedający"},
    {"value": "franchise", "label": "Franczyza"},
    {"value": "other", "label": "Inny"},
]

CLIENT_MEETING_TYPE_OPTIONS = [
    {"value": "consultation", "label": "Konsultacja"},
    {"value": "presentation", "label": "Prezentacja oferty"},
    {"value": "call", "label": "Telefon"},
    {"value": "online", "label": "Online"},
    {"value": "other", "label": "Inne"},
]

CLIENT_MEETING_STATUS_OPTIONS = [
    {"value": "planned", "label": "Zaplanowane"},
    {"value": "completed", "label": "Zrealizowane"},
    {"value": "cancelled", "label": "Odwołane"},
    {"value": "no_show", "label": "Brak klienta"},
]

DEFAULT_CLIENT_STATUS = "new"
DEFAULT_CLIENT_TYPE = "buyer"
STATUS_LABEL_BY_VALUE = {item["value"]: item["label"] for item in CLIENT_STATUS_OPTIONS}
CLIENT_TYPE_LABEL_BY_VALUE = {item["value"]: item["label"] for item in CLIENT_TYPE_OPTIONS}
CLIENT_MEETING_TYPE_LABEL_BY_VALUE = {item["value"]: item["label"] for item in CLIENT_MEETING_TYPE_OPTIONS}
CLIENT_MEETING_STATUS_LABEL_BY_VALUE = {item["value"]: item["label"] for item in CLIENT_MEETING_STATUS_OPTIONS}
CLIENT_ACTIVITY_FIELD_LABELS = {
    "first_name": "Imię",
    "last_name": "Nazwisko",
    "email": "E-mail",
    "phone": "Telefon",
    "city": "Miasto",
    "source_label": "Źródło",
    "notes": "Notatka",
    "status_code": "Status",
    "client_type": "Typ klienta",
    "owner_agent_id": "Opiekun",
    "last_contact_at": "Ostatni kontakt",
    "next_action_at": "Następny krok",
}


def _now_iso() -> str:
    return datetime.utcnow().isoformat(timespec="seconds")


def _normalize_text(value) -> str:
    text = str(value or "").strip().lower()
    replacements = {
        "ą": "a",
        "ć": "c",
        "ę": "e",
        "ł": "l",
        "ń": "n",
        "ó": "o",
        "ś": "s",
        "ż": "z",
        "ź": "z",
    }
    for src, dst in replacements.items():
        text = text.replace(src, dst)
    return " ".join(text.split())


def _normalize_phone(value) -> str:
    return "".join(ch for ch in str(value or "") if ch.isdigit())


def open_crm_clients_connection() -> sqlite3.Connection:
    db_path = storage_paths.crm_clients_db_path()
    db_path.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(db_path))
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA synchronous=NORMAL")
    conn.execute("PRAGMA foreign_keys=ON")
    return conn


def ensure_crm_clients_schema(conn: sqlite3.Connection) -> None:
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS crm_clients (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            first_name TEXT NOT NULL,
            last_name TEXT NOT NULL,
            email TEXT,
            phone TEXT,
            city TEXT,
            source_label TEXT,
            notes TEXT,
            status_code TEXT NOT NULL DEFAULT 'new',
            client_type TEXT NOT NULL DEFAULT 'buyer',
            owner_agent_id INTEGER NOT NULL,
            created_by_user_id INTEGER,
            last_contact_at TEXT,
            next_action_at TEXT,
            is_active INTEGER NOT NULL DEFAULT 1,
            is_archived INTEGER NOT NULL DEFAULT 0,
            normalized_first_name TEXT NOT NULL,
            normalized_last_name TEXT NOT NULL,
            normalized_full_name TEXT NOT NULL,
            normalized_email TEXT,
            normalized_phone TEXT,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
        );

        CREATE TABLE IF NOT EXISTS crm_client_status_history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            client_id INTEGER NOT NULL,
            previous_status_code TEXT,
            new_status_code TEXT NOT NULL,
            note TEXT,
            changed_by_user_id INTEGER,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES crm_clients(id) ON DELETE CASCADE
        );

        CREATE TABLE IF NOT EXISTS crm_client_offers (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            client_id INTEGER NOT NULL,
            offer_id INTEGER NOT NULL,
            relation_type TEXT NOT NULL DEFAULT 'matched',
            note TEXT,
            created_by_user_id INTEGER,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES crm_clients(id) ON DELETE CASCADE
        );

        CREATE TABLE IF NOT EXISTS crm_client_meetings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            client_id INTEGER NOT NULL,
            meeting_type TEXT NOT NULL DEFAULT 'consultation',
            meeting_status TEXT NOT NULL DEFAULT 'planned',
            start_at TEXT,
            end_at TEXT,
            location_label TEXT,
            notes TEXT,
            created_by_user_id INTEGER,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES crm_clients(id) ON DELETE CASCADE
        );

        CREATE TABLE IF NOT EXISTS crm_client_activity_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            client_id INTEGER NOT NULL,
            event_type TEXT NOT NULL,
            summary TEXT NOT NULL,
            payload_json TEXT,
            actor_user_id INTEGER,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (client_id) REFERENCES crm_clients(id) ON DELETE CASCADE
        );

        CREATE INDEX IF NOT EXISTS idx_crm_clients_owner_status
            ON crm_clients(owner_agent_id, status_code, is_archived, is_active);

        CREATE INDEX IF NOT EXISTS idx_crm_clients_last_name
            ON crm_clients(normalized_last_name, normalized_first_name);

        CREATE INDEX IF NOT EXISTS idx_crm_clients_full_name
            ON crm_clients(normalized_full_name);

        CREATE INDEX IF NOT EXISTS idx_crm_clients_email_phone
            ON crm_clients(normalized_email, normalized_phone);

        CREATE INDEX IF NOT EXISTS idx_crm_client_offers_client
            ON crm_client_offers(client_id, offer_id);

        CREATE UNIQUE INDEX IF NOT EXISTS uq_crm_client_offer_relation
            ON crm_client_offers(client_id, offer_id);

        CREATE INDEX IF NOT EXISTS idx_crm_client_meetings_client
            ON crm_client_meetings(client_id, start_at);

        CREATE INDEX IF NOT EXISTS idx_crm_client_activity_client
            ON crm_client_activity_log(client_id, created_at DESC);

        CREATE TRIGGER IF NOT EXISTS trg_crm_clients_updated_at
        AFTER UPDATE ON crm_clients
        FOR EACH ROW
        BEGIN
            UPDATE crm_clients
            SET updated_at = CURRENT_TIMESTAMP
            WHERE id = NEW.id;
        END;

        CREATE TRIGGER IF NOT EXISTS trg_crm_client_meetings_updated_at
        AFTER UPDATE ON crm_client_meetings
        FOR EACH ROW
        BEGIN
            UPDATE crm_client_meetings
            SET updated_at = CURRENT_TIMESTAMP
            WHERE id = NEW.id;
        END;
        """
    )


def initialize_crm_clients_db() -> Path:
    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        conn.commit()
    return storage_paths.crm_clients_db_path()


def _serialize_client_row(row: sqlite3.Row) -> dict:
    return {
        "id": int(row["id"]),
        "first_name": row["first_name"] or "",
        "last_name": row["last_name"] or "",
        "email": row["email"] or "",
        "phone": row["phone"] or "",
        "city": row["city"] or "",
        "source_label": row["source_label"] or "",
        "notes": row["notes"] or "",
        "status_code": row["status_code"] or DEFAULT_CLIENT_STATUS,
        "client_type": row["client_type"] or DEFAULT_CLIENT_TYPE,
        "owner_agent_id": int(row["owner_agent_id"] or 0),
        "created_by_user_id": int(row["created_by_user_id"] or 0) if row["created_by_user_id"] is not None else None,
        "last_contact_at": row["last_contact_at"] or "",
        "next_action_at": row["next_action_at"] or "",
        "is_active": int(row["is_active"] or 0),
        "is_archived": int(row["is_archived"] or 0),
        "created_at": row["created_at"] or "",
        "updated_at": row["updated_at"] or "",
        "offers_count": int(row["offers_count"] or 0) if "offers_count" in row.keys() else 0,
        "meetings_count": int(row["meetings_count"] or 0) if "meetings_count" in row.keys() else 0,
    }


def _serialize_meeting_row(row: sqlite3.Row) -> dict:
    return {
        "id": int(row["id"]),
        "client_id": int(row["client_id"]),
        "meeting_type": row["meeting_type"] or "consultation",
        "meeting_status": row["meeting_status"] or "planned",
        "start_at": row["start_at"] or "",
        "end_at": row["end_at"] or "",
        "location_label": row["location_label"] or "",
        "notes": row["notes"] or "",
        "created_by_user_id": int(row["created_by_user_id"] or 0) if row["created_by_user_id"] is not None else None,
        "created_at": row["created_at"] or "",
        "updated_at": row["updated_at"] or "",
        "client_first_name": row["client_first_name"] if "client_first_name" in row.keys() else "",
        "client_last_name": row["client_last_name"] if "client_last_name" in row.keys() else "",
        "owner_agent_id": int(row["owner_agent_id"] or 0) if "owner_agent_id" in row.keys() and row["owner_agent_id"] is not None else None,
    }


def _record_activity(
    conn: sqlite3.Connection,
    client_id: int,
    event_type: str,
    summary: str,
    actor_user_id: int | None,
    payload: dict | None = None,
) -> None:
    conn.execute(
        """
        INSERT INTO crm_client_activity_log (
            client_id, event_type, summary, payload_json, actor_user_id, created_at
        )
        VALUES (?, ?, ?, ?, ?, ?)
        """,
        (
            int(client_id),
            str(event_type or "").strip() or "event",
            str(summary or "").strip() or "Zdarzenie CRM",
            json.dumps(payload or {}, ensure_ascii=False) if payload is not None else None,
            actor_user_id,
            _now_iso(),
        ),
    )


def _record_status_change(
    conn: sqlite3.Connection,
    client_id: int,
    previous_status_code: str | None,
    new_status_code: str,
    changed_by_user_id: int | None,
    note: str = "",
) -> None:
    conn.execute(
        """
        INSERT INTO crm_client_status_history (
            client_id, previous_status_code, new_status_code, note, changed_by_user_id, created_at
        )
        VALUES (?, ?, ?, ?, ?, ?)
        """,
        (
            int(client_id),
            previous_status_code,
            str(new_status_code or DEFAULT_CLIENT_STATUS),
            str(note or "").strip(),
            changed_by_user_id,
            _now_iso(),
        ),
    )


def _normalize_client_payload(payload: dict) -> dict:
    first_name = str(payload.get("first_name") or "").strip()
    last_name = str(payload.get("last_name") or "").strip()
    email = str(payload.get("email") or "").strip()
    phone = str(payload.get("phone") or "").strip()
    city = str(payload.get("city") or "").strip()
    source_label = str(payload.get("source_label") or "").strip()
    notes = str(payload.get("notes") or "").strip()
    status_code = str(payload.get("status_code") or DEFAULT_CLIENT_STATUS).strip() or DEFAULT_CLIENT_STATUS
    client_type = str(payload.get("client_type") or DEFAULT_CLIENT_TYPE).strip() or DEFAULT_CLIENT_TYPE
    last_contact_at = str(payload.get("last_contact_at") or "").strip()
    next_action_at = str(payload.get("next_action_at") or "").strip()

    return {
        "first_name": first_name,
        "last_name": last_name,
        "email": email,
        "phone": phone,
        "city": city,
        "source_label": source_label,
        "notes": notes,
        "status_code": status_code,
        "client_type": client_type,
        "last_contact_at": last_contact_at,
        "next_action_at": next_action_at,
        "normalized_first_name": _normalize_text(first_name),
        "normalized_last_name": _normalize_text(last_name),
        "normalized_full_name": _normalize_text(f"{first_name} {last_name}"),
        "normalized_email": _normalize_text(email),
        "normalized_phone": _normalize_phone(phone),
    }


def _format_activity_value(field_name: str, value) -> str:
    if value in (None, ""):
        return "—"
    if field_name == "status_code":
        return STATUS_LABEL_BY_VALUE.get(str(value), str(value))
    if field_name == "client_type":
        return CLIENT_TYPE_LABEL_BY_VALUE.get(str(value), str(value))
    if field_name == "owner_agent_id":
        try:
            numeric_value = int(value)
        except Exception:
            return str(value)
        return f"Agent #{numeric_value}" if numeric_value > 0 else "—"
    return str(value)


def _build_client_change_log(current: dict, normalized: dict, owner_agent_id: int) -> list[dict]:
    changed_fields = []
    tracked_fields = (
        "first_name",
        "last_name",
        "email",
        "phone",
        "city",
        "source_label",
        "notes",
        "status_code",
        "client_type",
        "last_contact_at",
        "next_action_at",
    )

    for field_name in tracked_fields:
        before_value = current.get(field_name) or ""
        after_value = normalized.get(field_name) or ""
        if str(before_value) == str(after_value):
            continue
        changed_fields.append(
            {
                "field": field_name,
                "label": CLIENT_ACTIVITY_FIELD_LABELS.get(field_name, field_name),
                "before": _format_activity_value(field_name, before_value),
                "after": _format_activity_value(field_name, after_value),
            }
        )

    current_owner = int(current.get("owner_agent_id") or 0)
    next_owner = int(owner_agent_id or 0)
    if current_owner != next_owner:
        changed_fields.append(
            {
                "field": "owner_agent_id",
                "label": CLIENT_ACTIVITY_FIELD_LABELS["owner_agent_id"],
                "before": _format_activity_value("owner_agent_id", current_owner),
                "after": _format_activity_value("owner_agent_id", next_owner),
            }
        )

    return changed_fields


def get_client(client_id: int) -> dict | None:
    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        row = conn.execute(
            """
            SELECT
                c.*,
                (SELECT COUNT(*) FROM crm_client_offers co WHERE co.client_id = c.id) AS offers_count,
                (SELECT COUNT(*) FROM crm_client_meetings cm WHERE cm.client_id = c.id) AS meetings_count
            FROM crm_clients c
            WHERE c.id = ?
            LIMIT 1
            """,
            (int(client_id),),
        ).fetchone()
        return _serialize_client_row(row) if row else None


def get_client_details(client_id: int) -> dict | None:
    client = get_client(client_id)
    if not client:
        return None

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        offer_rows = conn.execute(
            """
            SELECT
                co.offer_id,
                co.relation_type,
                COALESCE(co.note, '') AS relation_note,
                co.created_at AS linked_at
            FROM crm_client_offers co
            WHERE co.client_id = ?
            ORDER BY co.created_at DESC, co.id DESC
            """,
            (int(client_id),),
        ).fetchall()
        activity_rows = conn.execute(
            """
            SELECT
                event_type,
                summary,
                COALESCE(payload_json, '') AS payload_json,
                actor_user_id,
                created_at
            FROM crm_client_activity_log
            WHERE client_id = ?
            ORDER BY created_at DESC, id DESC
            LIMIT 20
            """,
            (int(client_id),),
        ).fetchall()
        meeting_rows = conn.execute(
            """
            SELECT
                cm.*
            FROM crm_client_meetings cm
            WHERE cm.client_id = ?
            ORDER BY
                CASE cm.meeting_status
                    WHEN 'planned' THEN 0
                    WHEN 'completed' THEN 1
                    ELSE 2
                END,
                COALESCE(cm.start_at, '') ASC,
                cm.id DESC
            """,
            (int(client_id),),
        ).fetchall()

    client["offers"] = [
        {
            "offer_id": int(row["offer_id"]),
            "relation_type": row["relation_type"] or "matched",
            "relation_note": row["relation_note"] or "",
            "linked_at": row["linked_at"] or "",
        }
        for row in offer_rows
    ]
    client["activity"] = []
    for row in activity_rows:
        try:
            payload = json.loads(row["payload_json"]) if row["payload_json"] else {}
        except Exception:
            payload = {}
        client["activity"].append(
            {
                "event_type": row["event_type"] or "",
                "summary": row["summary"] or "",
                "payload": payload,
                "actor_user_id": int(row["actor_user_id"] or 0) if row["actor_user_id"] is not None else None,
                "created_at": row["created_at"] or "",
            }
        )
    client["meetings"] = [_serialize_meeting_row(row) for row in meeting_rows]
    return client


def list_client_meetings(client_id: int) -> list[dict]:
    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        rows = conn.execute(
            """
            SELECT
                cm.*
            FROM crm_client_meetings cm
            WHERE cm.client_id = ?
            ORDER BY
                CASE cm.meeting_status
                    WHEN 'planned' THEN 0
                    WHEN 'completed' THEN 1
                    ELSE 2
                END,
                COALESCE(cm.start_at, '') ASC,
                cm.id DESC
            """,
            (int(client_id),),
        ).fetchall()
    return [_serialize_meeting_row(row) for row in rows]


def list_agent_calendar_meetings(owner_agent_id: int | None = None) -> list[dict]:
    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        params = []
        owner_sql = ""
        if owner_agent_id is not None:
            owner_sql = " AND c.owner_agent_id = ?"
            params.append(int(owner_agent_id))

        rows = conn.execute(
            f"""
            SELECT
                cm.*,
                c.first_name AS client_first_name,
                c.last_name AS client_last_name,
                c.owner_agent_id
            FROM crm_client_meetings cm
            JOIN crm_clients c ON c.id = cm.client_id
            WHERE c.is_archived = 0
              {owner_sql}
            ORDER BY COALESCE(cm.start_at, '') ASC, cm.id DESC
            """,
            params,
        ).fetchall()
    return [_serialize_meeting_row(row) for row in rows]


def create_client_meeting(
    client_id: int,
    payload: dict,
    *,
    actor_user_id: int | None,
) -> dict | None:
    client = get_client(client_id)
    if not client:
        return None

    start_at = str(payload.get("start_at") or "").strip()
    if not start_at:
        raise ValueError("Termin spotkania jest wymagany.")

    meeting_type = str(payload.get("meeting_type") or "consultation").strip() or "consultation"
    meeting_status = str(payload.get("meeting_status") or "planned").strip() or "planned"
    end_at = str(payload.get("end_at") or "").strip()
    location_label = str(payload.get("location_label") or "").strip()
    notes = str(payload.get("notes") or "").strip()
    now = _now_iso()

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        cursor = conn.execute(
            """
            INSERT INTO crm_client_meetings (
                client_id, meeting_type, meeting_status, start_at, end_at,
                location_label, notes, created_by_user_id, created_at, updated_at
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                int(client_id),
                meeting_type,
                meeting_status,
                start_at,
                end_at or None,
                location_label,
                notes,
                actor_user_id,
                now,
                now,
            ),
        )
        meeting_id = int(cursor.lastrowid)
        _record_activity(
            conn,
            int(client_id),
            "meeting_created",
            f"Dodano spotkanie: {CLIENT_MEETING_TYPE_LABEL_BY_VALUE.get(meeting_type, meeting_type)}",
            actor_user_id,
            payload={
                "meeting_id": meeting_id,
                "meeting_type": meeting_type,
                "meeting_status": meeting_status,
                "start_at": start_at,
                "end_at": end_at,
                "location_label": location_label,
            },
        )
        conn.commit()

    meetings = list_client_meetings(int(client_id))
    for meeting in meetings:
        if int(meeting["id"]) == meeting_id:
            return meeting
    return None


def update_client_meeting(
    client_id: int,
    meeting_id: int,
    payload: dict,
    *,
    actor_user_id: int | None,
) -> dict | None:
    client = get_client(client_id)
    if not client:
        return None

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        current_row = conn.execute(
            """
            SELECT *
            FROM crm_client_meetings
            WHERE id = ? AND client_id = ?
            LIMIT 1
            """,
            (int(meeting_id), int(client_id)),
        ).fetchone()
        if not current_row:
            return None

        current = _serialize_meeting_row(current_row)
        meeting_type = str(payload.get("meeting_type") or current["meeting_type"]).strip() or current["meeting_type"]
        meeting_status = str(payload.get("meeting_status") or current["meeting_status"]).strip() or current["meeting_status"]
        start_at = str(payload.get("start_at") or current["start_at"]).strip()
        end_at = str(payload.get("end_at") or current["end_at"]).strip()
        location_label = str(payload.get("location_label") or current["location_label"]).strip()
        notes = str(payload.get("notes") or current["notes"]).strip()
        if not start_at:
            raise ValueError("Termin spotkania jest wymagany.")

        conn.execute(
            """
            UPDATE crm_client_meetings
            SET
                meeting_type = ?,
                meeting_status = ?,
                start_at = ?,
                end_at = ?,
                location_label = ?,
                notes = ?,
                updated_at = ?
            WHERE id = ? AND client_id = ?
            """,
            (
                meeting_type,
                meeting_status,
                start_at,
                end_at or None,
                location_label,
                notes,
                _now_iso(),
                int(meeting_id),
                int(client_id),
            ),
        )
        _record_activity(
            conn,
            int(client_id),
            "meeting_updated",
            f"Zaktualizowano spotkanie: {CLIENT_MEETING_TYPE_LABEL_BY_VALUE.get(meeting_type, meeting_type)}",
            actor_user_id,
            payload={
                "meeting_id": int(meeting_id),
                "meeting_type": meeting_type,
                "meeting_status": meeting_status,
                "start_at": start_at,
                "end_at": end_at,
                "location_label": location_label,
            },
        )
        conn.commit()

    meetings = list_client_meetings(int(client_id))
    for meeting in meetings:
        if int(meeting["id"]) == int(meeting_id):
            return meeting
    return None


def delete_client_meeting(
    client_id: int,
    meeting_id: int,
    *,
    actor_user_id: int | None,
) -> bool:
    client = get_client(client_id)
    if not client:
        return False

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        row = conn.execute(
            """
            SELECT *
            FROM crm_client_meetings
            WHERE id = ? AND client_id = ?
            LIMIT 1
            """,
            (int(meeting_id), int(client_id)),
        ).fetchone()
        if not row:
            return False

        meeting = _serialize_meeting_row(row)
        cursor = conn.execute(
            """
            DELETE FROM crm_client_meetings
            WHERE id = ? AND client_id = ?
            """,
            (int(meeting_id), int(client_id)),
        )
        _record_activity(
            conn,
            int(client_id),
            "meeting_deleted",
            f"Usunięto spotkanie: {CLIENT_MEETING_TYPE_LABEL_BY_VALUE.get(meeting['meeting_type'], meeting['meeting_type'])}",
            actor_user_id,
            payload={
                "meeting_id": int(meeting_id),
                "meeting_type": meeting.get("meeting_type"),
                "meeting_status": meeting.get("meeting_status"),
                "start_at": meeting.get("start_at"),
            },
        )
        conn.commit()
        return int(cursor.rowcount or 0) > 0


def detect_potential_duplicates(payload: dict, exclude_client_id: int | None = None) -> list[dict]:
    normalized = _normalize_client_payload(payload)
    clauses = []
    params = []

    if normalized["normalized_last_name"]:
        clauses.append("normalized_last_name = ?")
        params.append(normalized["normalized_last_name"])
    if normalized["normalized_first_name"] and normalized["normalized_last_name"]:
        clauses.append("(normalized_first_name = ? AND normalized_last_name = ?)")
        params.extend([normalized["normalized_first_name"], normalized["normalized_last_name"]])
    if normalized["normalized_email"]:
        clauses.append("(normalized_email <> '' AND normalized_email = ?)")
        params.append(normalized["normalized_email"])
    if normalized["normalized_phone"]:
        clauses.append("(normalized_phone <> '' AND normalized_phone = ?)")
        params.append(normalized["normalized_phone"])

    if not clauses:
        return []

    sql = f"""
        SELECT
            c.*,
            (SELECT COUNT(*) FROM crm_client_offers co WHERE co.client_id = c.id) AS offers_count,
            (SELECT COUNT(*) FROM crm_client_meetings cm WHERE cm.client_id = c.id) AS meetings_count
        FROM crm_clients c
        WHERE c.is_archived = 0
          AND ({' OR '.join(clauses)})
    """
    if exclude_client_id is not None:
        sql += " AND c.id != ?"
        params.append(int(exclude_client_id))

    sql += " ORDER BY c.updated_at DESC, c.id DESC LIMIT 12"

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        rows = conn.execute(sql, params).fetchall()
        return [_serialize_client_row(row) for row in rows]


def list_clients(
    *,
    query: str = "",
    status_code: str = "",
    client_type: str = "",
    owner_agent_id: int | None = None,
    limit: int = 200,
) -> list[dict]:
    search = _normalize_text(query)
    params = []
    where = ["c.is_archived = 0"]

    if status_code:
        where.append("c.status_code = ?")
        params.append(status_code)
    if client_type:
        where.append("c.client_type = ?")
        params.append(client_type)
    if owner_agent_id is not None:
        where.append("c.owner_agent_id = ?")
        params.append(int(owner_agent_id))
    if search:
        like = f"%{search}%"
        where.append(
            """
            (
                c.normalized_full_name LIKE ?
                OR c.normalized_last_name LIKE ?
                OR COALESCE(c.normalized_email, '') LIKE ?
                OR COALESCE(c.normalized_phone, '') LIKE ?
                OR COALESCE(LOWER(c.city), '') LIKE ?
                OR COALESCE(LOWER(c.source_label), '') LIKE ?
                OR COALESCE(LOWER(c.notes), '') LIKE ?
            )
            """
        )
        params.extend([like, like, like, like, like, like, like])

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        rows = conn.execute(
            f"""
            SELECT
                c.*,
                (SELECT COUNT(*) FROM crm_client_offers co WHERE co.client_id = c.id) AS offers_count,
                (SELECT COUNT(*) FROM crm_client_meetings cm WHERE cm.client_id = c.id) AS meetings_count
            FROM crm_clients c
            WHERE {' AND '.join(where)}
            ORDER BY c.updated_at DESC, c.id DESC
            LIMIT ?
            """,
            [*params, int(limit)],
        ).fetchall()
        return [_serialize_client_row(row) for row in rows]


def create_client(
    payload: dict,
    *,
    owner_agent_id: int,
    created_by_user_id: int | None,
    force_create: bool = False,
) -> tuple[dict, list[dict]]:
    normalized = _normalize_client_payload(payload)
    duplicates = detect_potential_duplicates(payload)
    if duplicates and not force_create:
        return {}, duplicates

    now = _now_iso()
    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        cursor = conn.execute(
            """
            INSERT INTO crm_clients (
                first_name, last_name, email, phone, city, source_label, notes, status_code, client_type,
                owner_agent_id, created_by_user_id, last_contact_at, next_action_at,
                normalized_first_name, normalized_last_name, normalized_full_name,
                normalized_email, normalized_phone, created_at, updated_at
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                normalized["first_name"],
                normalized["last_name"],
                normalized["email"],
                normalized["phone"],
                normalized["city"],
                normalized["source_label"],
                normalized["notes"],
                normalized["status_code"],
                normalized["client_type"],
                int(owner_agent_id),
                created_by_user_id,
                normalized["last_contact_at"] or None,
                normalized["next_action_at"] or None,
                normalized["normalized_first_name"],
                normalized["normalized_last_name"],
                normalized["normalized_full_name"],
                normalized["normalized_email"],
                normalized["normalized_phone"],
                now,
                now,
            ),
        )
        client_id = int(cursor.lastrowid)
        _record_status_change(
            conn,
            client_id,
            previous_status_code=None,
            new_status_code=normalized["status_code"],
            changed_by_user_id=created_by_user_id,
            note="Utworzenie klienta",
        )
        _record_activity(
            conn,
            client_id,
            "client_created",
            f"Dodano klienta {normalized['first_name']} {normalized['last_name']}".strip(),
            created_by_user_id,
            payload={"owner_agent_id": int(owner_agent_id)},
        )
        conn.commit()
    return get_client(client_id) or {}, duplicates


def update_client(
    client_id: int,
    payload: dict,
    *,
    owner_agent_id: int,
    actor_user_id: int | None,
    force_save: bool = False,
) -> tuple[dict, list[dict]]:
    current = get_client(client_id)
    if not current:
        return {}, []

    normalized = _normalize_client_payload(payload)
    changed_fields = _build_client_change_log(current, normalized, owner_agent_id)
    duplicates = detect_potential_duplicates(payload, exclude_client_id=client_id)
    if duplicates and not force_save:
        return {}, duplicates

    now = _now_iso()
    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        conn.execute(
            """
            UPDATE crm_clients
            SET
                first_name = ?,
                last_name = ?,
                email = ?,
                phone = ?,
                city = ?,
                source_label = ?,
                notes = ?,
                status_code = ?,
                client_type = ?,
                owner_agent_id = ?,
                last_contact_at = ?,
                next_action_at = ?,
                normalized_first_name = ?,
                normalized_last_name = ?,
                normalized_full_name = ?,
                normalized_email = ?,
                normalized_phone = ?,
                updated_at = ?
            WHERE id = ?
            """,
            (
                normalized["first_name"],
                normalized["last_name"],
                normalized["email"],
                normalized["phone"],
                normalized["city"],
                normalized["source_label"],
                normalized["notes"],
                normalized["status_code"],
                normalized["client_type"],
                int(owner_agent_id),
                normalized["last_contact_at"] or None,
                normalized["next_action_at"] or None,
                normalized["normalized_first_name"],
                normalized["normalized_last_name"],
                normalized["normalized_full_name"],
                normalized["normalized_email"],
                normalized["normalized_phone"],
                now,
                int(client_id),
            ),
        )
        if current["status_code"] != normalized["status_code"]:
            _record_status_change(
                conn,
                int(client_id),
                previous_status_code=current["status_code"],
                new_status_code=normalized["status_code"],
                changed_by_user_id=actor_user_id,
                note="Zmiana przy edycji klienta",
            )
        if changed_fields:
            changed_labels = ", ".join(item["label"] for item in changed_fields[:4])
            if len(changed_fields) > 4:
                changed_labels += f" i {len(changed_fields) - 4} kolejne"
            _record_activity(
                conn,
                int(client_id),
                "client_updated",
                f"Zaktualizowano pola klienta: {changed_labels}",
                actor_user_id,
                payload={
                    "owner_agent_id": int(owner_agent_id),
                    "changes": changed_fields,
                },
            )
        conn.commit()
    return get_client(client_id) or {}, duplicates


def update_client_status(
    client_id: int,
    status_code: str,
    *,
    actor_user_id: int | None,
    note: str = "",
) -> dict | None:
    current = get_client(client_id)
    if not current:
        return None

    new_status_code = str(status_code or DEFAULT_CLIENT_STATUS).strip() or DEFAULT_CLIENT_STATUS
    if current["status_code"] == new_status_code:
        return current

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        conn.execute(
            "UPDATE crm_clients SET status_code = ?, updated_at = ? WHERE id = ?",
            (new_status_code, _now_iso(), int(client_id)),
        )
        _record_status_change(
            conn,
            int(client_id),
            previous_status_code=current["status_code"],
            new_status_code=new_status_code,
            changed_by_user_id=actor_user_id,
            note=note,
        )
        _record_activity(
            conn,
            int(client_id),
            "status_changed",
            f"Zmieniono status: {_format_activity_value('status_code', current['status_code'])} -> {_format_activity_value('status_code', new_status_code)}",
            actor_user_id,
            payload={
                "from": current["status_code"],
                "to": new_status_code,
                "changes": [
                    {
                        "field": "status_code",
                        "label": CLIENT_ACTIVITY_FIELD_LABELS["status_code"],
                        "before": _format_activity_value("status_code", current["status_code"]),
                        "after": _format_activity_value("status_code", new_status_code),
                    }
                ],
            },
        )
        conn.commit()

    return get_client(client_id)


def list_clients_for_offer(offer_id: int, *, owner_agent_id: int | None = None) -> list[dict]:
    params = [int(offer_id)]
    owner_sql = ""
    if owner_agent_id is not None:
        owner_sql = " AND c.owner_agent_id = ?"
        params.append(int(owner_agent_id))

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        rows = conn.execute(
            f"""
            SELECT
                c.*,
                co.relation_type,
                COALESCE(co.note, '') AS relation_note,
                co.created_at AS linked_at,
                co.created_by_user_id AS linked_by_user_id,
                (SELECT COUNT(*) FROM crm_client_offers co2 WHERE co2.client_id = c.id) AS offers_count,
                (SELECT COUNT(*) FROM crm_client_meetings cm WHERE cm.client_id = c.id) AS meetings_count
            FROM crm_client_offers co
            JOIN crm_clients c ON c.id = co.client_id
            WHERE co.offer_id = ?
              AND c.is_archived = 0
              {owner_sql}
            ORDER BY co.created_at DESC, co.id DESC
            """,
            params,
        ).fetchall()

    result = []
    for row in rows:
        item = _serialize_client_row(row)
        item["relation_type"] = row["relation_type"] or "matched"
        item["relation_note"] = row["relation_note"] or ""
        item["linked_at"] = row["linked_at"] or ""
        item["linked_by_user_id"] = (
            int(row["linked_by_user_id"] or 0)
            if row["linked_by_user_id"] is not None
            else None
        )
        result.append(item)
    return result


def attach_client_to_offer(
    client_id: int,
    offer_id: int,
    *,
    relation_type: str = "matched",
    note: str = "",
    actor_user_id: int | None,
) -> dict | None:
    client = get_client(client_id)
    if not client:
        return None

    normalized_relation = str(relation_type or "matched").strip() or "matched"
    normalized_note = str(note or "").strip()
    now = _now_iso()

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        existing = conn.execute(
            """
            SELECT id
            FROM crm_client_offers
            WHERE client_id = ? AND offer_id = ?
            LIMIT 1
            """,
            (int(client_id), int(offer_id)),
        ).fetchone()

        if existing:
            conn.execute(
                """
                UPDATE crm_client_offers
                SET relation_type = ?, note = ?
                WHERE client_id = ? AND offer_id = ?
                """,
                (normalized_relation, normalized_note, int(client_id), int(offer_id)),
            )
            action_summary = f"Zaktualizowano powiązanie z ofertą #{offer_id}"
            event_type = "offer_relation_updated"
        else:
            conn.execute(
                """
                INSERT INTO crm_client_offers (
                    client_id, offer_id, relation_type, note, created_by_user_id, created_at
                )
                VALUES (?, ?, ?, ?, ?, ?)
                """,
                (
                    int(client_id),
                    int(offer_id),
                    normalized_relation,
                    normalized_note,
                    actor_user_id,
                    now,
                ),
            )
            action_summary = f"Przypisano klienta do oferty #{offer_id}"
            event_type = "offer_relation_created"

        _record_activity(
            conn,
            int(client_id),
            event_type,
            action_summary,
            actor_user_id,
            payload={
                "offer_id": int(offer_id),
                "relation_type": normalized_relation,
                "note": normalized_note,
            },
        )
        conn.commit()

    items = list_clients_for_offer(int(offer_id))
    for item in items:
        if int(item["id"]) == int(client_id):
            return item
    return get_client(client_id)


def detach_client_from_offer(
    client_id: int,
    offer_id: int,
    *,
    actor_user_id: int | None,
) -> bool:
    client = get_client(client_id)
    if not client:
        return False

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        cursor = conn.execute(
            """
            DELETE FROM crm_client_offers
            WHERE client_id = ? AND offer_id = ?
            """,
            (int(client_id), int(offer_id)),
        )
        if int(cursor.rowcount or 0) < 1:
            return False

        _record_activity(
            conn,
            int(client_id),
            "offer_relation_deleted",
            f"Odpięto klienta od oferty #{offer_id}",
            actor_user_id,
            payload={"offer_id": int(offer_id)},
        )
        conn.commit()
    return True


def delete_client(client_id: int, *, actor_user_id: int | None) -> bool:
    client = get_client(client_id)
    if not client:
        return False

    with open_crm_clients_connection() as conn:
        ensure_crm_clients_schema(conn)
        _record_activity(
            conn,
            int(client_id),
            "client_deleted",
            f"Usunięto klienta {client.get('first_name', '')} {client.get('last_name', '')}".strip(),
            actor_user_id,
            payload={"client_id": int(client_id)},
        )
        cursor = conn.execute(
            "DELETE FROM crm_clients WHERE id = ?",
            (int(client_id),),
        )
        conn.commit()
        return int(cursor.rowcount or 0) > 0
