import json
from datetime import datetime

from modules.connector import connection


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


def _stringify_scalar(value):
    if isinstance(value, list):
        return ", ".join(str(item).strip() for item in value if str(item).strip()) or None
    return (str(value).strip() if value not in (None, "") else None)


def ensure_valuation_leads_schema(conn) -> None:
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS crm_valuation_leads (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            property_type TEXT NOT NULL,
            full_name TEXT,
            phone TEXT,
            email TEXT,
            preferred_contact TEXT,
            city TEXT,
            district TEXT,
            street TEXT,
            building_number TEXT,
            postal_code TEXT,
            region TEXT,
            location_description TEXT,
            primary_goal TEXT,
            other_goal_details TEXT,
            sale_timeline TEXT,
            technical_condition TEXT,
            ownership_form TEXT,
            source TEXT NOT NULL,
            status TEXT NOT NULL DEFAULT 'new',
            payload_json TEXT NOT NULL,
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        )
        """
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_crm_valuation_leads_created_at ON crm_valuation_leads(created_at DESC)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_crm_valuation_leads_status ON crm_valuation_leads(status)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_crm_valuation_leads_property_type ON crm_valuation_leads(property_type)"
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_crm_valuation_leads_region ON crm_valuation_leads(region)"
    )


def save_valuation_lead(payload: dict) -> int:
    now = _now_iso()
    location = payload.get("location") or {}
    contact_data = payload.get("contactData") or {}
    client_goal = payload.get("clientGoal") or {}
    property_details = payload.get("propertyDetails") or {}

    with connection() as conn:
        ensure_valuation_leads_schema(conn)
        conn.execute(
            """
            INSERT INTO crm_valuation_leads (
                property_type,
                full_name,
                phone,
                email,
                preferred_contact,
                city,
                district,
                street,
                building_number,
                postal_code,
                region,
                location_description,
                primary_goal,
                other_goal_details,
                sale_timeline,
                technical_condition,
                ownership_form,
                source,
                status,
                payload_json,
                created_at,
                updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'new', ?, ?, ?)
            """,
            (
                payload.get("propertyType"),
                _stringify_scalar(contact_data.get("fullName")),
                _stringify_scalar(contact_data.get("phone")),
                _stringify_scalar(contact_data.get("email")),
                _stringify_scalar(contact_data.get("preferredContact")),
                _stringify_scalar(location.get("city")),
                _stringify_scalar(location.get("district")),
                _stringify_scalar(location.get("street")),
                _stringify_scalar(location.get("buildingNumber")),
                _stringify_scalar(location.get("postalCode")),
                _stringify_scalar(location.get("region")),
                _stringify_scalar(location.get("locationDescription")),
                _stringify_scalar(client_goal.get("primaryGoal")),
                _stringify_scalar(client_goal.get("otherGoalDetails")),
                _stringify_scalar(client_goal.get("saleTimeline")),
                _stringify_scalar(property_details.get("technicalCondition")),
                _stringify_scalar(property_details.get("ownershipForm")),
                payload.get("source") or "investment-nieruchomosci.com valuation form",
                json.dumps(payload, ensure_ascii=False),
                payload.get("createdAt") or now,
                now,
            ),
        )
        lead_id = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])
        conn.commit()
        return lead_id
