import json
import sqlite3
from datetime import datetime

from modules.core import storage_paths
from modules.core.platform_log_queries import list_lead_log_rows_after

ALLOWED_INBOX_STATUSES = {"new", "reviewed", "converted", "ignored", "duplicate"}
ALLOWED_LEAD_STAGES = {"new", "contacted", "qualified", "offer_sent", "negotiation", "won", "lost"}
ALLOWED_PRIORITIES = {"low", "normal", "high"}


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


def _connect() -> sqlite3.Connection:
    db_path = storage_paths.platform_logs_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")
    return conn


def ensure_leady_schema(conn: sqlite3.Connection) -> None:
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS lead_inbox (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            platform_log_id INTEGER NOT NULL UNIQUE,
            created_at TEXT NOT NULL,
            platform TEXT,
            phone TEXT,
            email TEXT,
            message TEXT,
            offer_url TEXT,
            platform_page_url TEXT,
            ip TEXT,
            inbox_status TEXT NOT NULL DEFAULT 'new',
            assigned_agent_id INTEGER,
            crm_lead_id INTEGER,
            notes TEXT,
            converted_at TEXT,
            converted_by INTEGER
        )
        """
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_lead_inbox_status ON lead_inbox(inbox_status)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_lead_inbox_platform ON lead_inbox(platform)"
    )
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS crm_leads (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            source TEXT NOT NULL,
            source_ref TEXT NOT NULL,
            name TEXT,
            phone TEXT,
            email TEXT,
            platform TEXT,
            offer_url TEXT,
            owner_agent_id INTEGER,
            stage TEXT NOT NULL DEFAULT 'new',
            lost_reason TEXT,
            priority TEXT NOT NULL DEFAULT 'normal',
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL,
            closed_at TEXT
        )
        """
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_crm_leads_stage ON crm_leads(stage)"
    )
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS crm_lead_events (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            lead_id INTEGER NOT NULL,
            event_type TEXT NOT NULL,
            from_stage TEXT,
            to_stage TEXT,
            note TEXT,
            created_by INTEGER,
            created_at TEXT NOT NULL
        )
        """
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_crm_lead_events_lead_id ON crm_lead_events(lead_id)"
    )


def sync_inbox_from_platform_logs(conn: sqlite3.Connection) -> int:
    ensure_leady_schema(conn)

    row = conn.execute("SELECT MAX(platform_log_id) AS max_id FROM lead_inbox").fetchone()
    max_seen = int(row["max_id"] or 0)

    logs = list_lead_log_rows_after(conn, max_seen)

    inserted = 0
    for log_row in logs:
        payload_raw = log_row["payload"] or "{}"
        try:
            payload = json.loads(payload_raw)
        except json.JSONDecodeError:
            payload = {}

        cursor = conn.execute(
            """
            INSERT OR IGNORE INTO lead_inbox (
                platform_log_id,
                created_at,
                platform,
                phone,
                email,
                message,
                offer_url,
                platform_page_url,
                ip,
                assigned_agent_id,
                inbox_status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'new')
            """,
            (
                log_row["id"],
                log_row["created_at"] or _now_iso(),
                payload.get("platform"),
                payload.get("phone"),
                payload.get("email"),
                payload.get("message"),
                payload.get("offer_url"),
                payload.get("platform_page_url"),
                payload.get("ip"),
                payload.get("agent_id") if payload.get("platform") == "investment" else None,
            ),
        )
        inserted += cursor.rowcount
    return inserted


def get_inbox_by_platform_log_ids(conn: sqlite3.Connection, platform_log_ids: list[int]) -> dict[int, dict]:
    ensure_leady_schema(conn)
    if not platform_log_ids:
        return {}

    placeholders = ",".join("?" for _ in platform_log_ids)
    rows = conn.execute(
        f"""
        SELECT
            li.id,
            li.platform_log_id,
            li.inbox_status,
            li.assigned_agent_id,
            li.crm_lead_id,
            li.notes,
            cl.name AS crm_lead_name,
            cl.priority AS crm_lead_priority
        FROM lead_inbox li
        LEFT JOIN crm_leads cl ON cl.id = li.crm_lead_id
        WHERE li.platform_log_id IN ({placeholders})
        """,
        tuple(platform_log_ids),
    ).fetchall()

    result = {}
    for row in rows:
        result[int(row["platform_log_id"])] = {
            "inbox_id": int(row["id"]),
            "inbox_status": row["inbox_status"] or "new",
            "assigned_agent_id": row["assigned_agent_id"],
            "crm_lead_id": row["crm_lead_id"],
            "notes": row["notes"] or "",
            "crm_lead_name": row["crm_lead_name"] or "",
            "crm_lead_priority": row["crm_lead_priority"] or "",
        }
    return result


def convert_inbox_to_crm_lead(
    conn: sqlite3.Connection,
    inbox_id: int,
    *,
    created_by: int | None,
    name: str | None = None,
    owner_agent_id: int | None = None,
    stage: str = "new",
    priority: str = "normal",
    note: str | None = None,
) -> tuple[int, int]:
    ensure_leady_schema(conn)

    stage = (stage or "new").strip().lower()
    if stage not in ALLOWED_LEAD_STAGES:
        raise ValueError("Nieprawidłowy stage")

    priority = (priority or "normal").strip().lower()
    if priority not in ALLOWED_PRIORITIES:
        raise ValueError("Nieprawidłowy priority")

    inbox_row = conn.execute(
        """
        SELECT *
        FROM lead_inbox
        WHERE id = ?
        """,
        (inbox_id,),
    ).fetchone()
    if not inbox_row:
        raise ValueError("Lead inbox nie istnieje")
    if inbox_row["crm_lead_id"]:
        raise ValueError("Lead został już skonwertowany")

    now = _now_iso()
    source_ref = f"lead_inbox:{inbox_id}"

    if owner_agent_id is None and inbox_row["assigned_agent_id"] is not None:
        owner_agent_id = int(inbox_row["assigned_agent_id"])

    conn.execute(
        """
        INSERT INTO crm_leads (
            source, source_ref, name, phone, email, platform, offer_url,
            owner_agent_id, stage, priority, created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """,
        (
            "platform",
            source_ref,
            (name or "").strip() or None,
            inbox_row["phone"],
            inbox_row["email"],
            inbox_row["platform"],
            inbox_row["offer_url"],
            owner_agent_id,
            stage,
            priority,
            now,
            now,
        ),
    )
    crm_lead_id = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])

    conn.execute(
        """
        INSERT INTO crm_lead_events (
            lead_id, event_type, from_stage, to_stage, note, created_by, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
        (
            crm_lead_id,
            "lead_created",
            None,
            stage,
            (note or "").strip() or None,
            created_by,
            now,
        ),
    )

    conn.execute(
        """
        UPDATE lead_inbox
        SET inbox_status = 'converted',
            crm_lead_id = ?,
            assigned_agent_id = COALESCE(?, assigned_agent_id),
            notes = CASE
                WHEN ? IS NOT NULL AND ? != '' THEN ?
                ELSE notes
            END,
            converted_at = ?,
            converted_by = ?
        WHERE id = ?
        """,
        (
            crm_lead_id,
            owner_agent_id,
            note,
            note,
            note,
            now,
            created_by,
            inbox_id,
        ),
    )

    return inbox_id, crm_lead_id


def update_inbox_status(
    conn: sqlite3.Connection,
    inbox_id: int,
    *,
    inbox_status: str | None = None,
    assigned_agent_id: int | None = None,
    notes: str | None = None,
    lead_name: str | None = None,
    lead_priority: str | None = None,
) -> None:
    ensure_leady_schema(conn)

    row = conn.execute("SELECT id, crm_lead_id FROM lead_inbox WHERE id = ?", (inbox_id,)).fetchone()
    if not row:
        raise ValueError("Lead inbox nie istnieje")

    updates = []
    values = []

    if inbox_status is not None:
        normalized = inbox_status.strip().lower()
        if normalized not in ALLOWED_INBOX_STATUSES:
            raise ValueError("Nieprawidłowy inbox_status")
        updates.append("inbox_status = ?")
        values.append(normalized)

    if assigned_agent_id is not None:
        updates.append("assigned_agent_id = ?")
        values.append(assigned_agent_id)

    if notes is not None:
        updates.append("notes = ?")
        values.append(notes.strip())

    if not updates:
        return

    values.append(inbox_id)
    conn.execute(
        f"UPDATE lead_inbox SET {', '.join(updates)} WHERE id = ?",
        tuple(values),
    )

    crm_lead_id = row["crm_lead_id"]
    if crm_lead_id and (lead_name is not None or lead_priority is not None or assigned_agent_id is not None):
        lead_updates = ["updated_at = ?"]
        lead_values = [_now_iso()]

        if lead_name is not None:
            lead_updates.append("name = ?")
            lead_values.append((lead_name or "").strip() or None)

        if lead_priority is not None:
            normalized_priority = (lead_priority or "normal").strip().lower()
            if normalized_priority not in ALLOWED_PRIORITIES:
                raise ValueError("Nieprawidłowy priority")
            lead_updates.append("priority = ?")
            lead_values.append(normalized_priority)

        if assigned_agent_id is not None:
            lead_updates.append("owner_agent_id = ?")
            lead_values.append(assigned_agent_id)

        lead_values.append(crm_lead_id)
        conn.execute(
            f"UPDATE crm_leads SET {', '.join(lead_updates)} WHERE id = ?",
            tuple(lead_values),
        )


def open_leady_connection() -> sqlite3.Connection:
    conn = _connect()
    ensure_leady_schema(conn)
    return conn
