import re
from datetime import datetime
from threading import Lock

from flask import current_app
from sqlalchemy import create_engine, text

from .. import db
from ..models import (
    ExternalLeadSync,
    Lead,
    LeadAssignmentHistory,
    LeadLocationAssignmentRule,
    LeadSource,
    LeadStatus,
)

_EXTERNAL_ENGINE = None
_EXTERNAL_ENGINE_URI = None
_EXTERNAL_ENGINE_LOCK = Lock()


INDIA_REGIONS = {
    "north": {
        "chandigarh",
        "delhi",
        "haryana",
        "himachal pradesh",
        "jammu and kashmir",
        "ladakh",
        "punjab",
        "uttar pradesh",
        "uttarakhand",
    },
    "south": {
        "andaman and nicobar islands",
        "andhra pradesh",
        "karnataka",
        "kerala",
        "lakshadweep",
        "puducherry",
        "tamil nadu",
        "telangana",
    },
    "east": {
        "bihar",
        "jharkhand",
        "odisha",
        "west bengal",
    },
    "west": {
        "dadra and nagar haveli and daman and diu",
        "goa",
        "gujarat",
        "maharashtra",
        "rajasthan",
    },
    "central": {
        "chhattisgarh",
        "madhya pradesh",
    },
    "north_east": {
        "arunachal pradesh",
        "assam",
        "manipur",
        "meghalaya",
        "mizoram",
        "nagaland",
        "sikkim",
        "tripura",
    },
}

INDIA_STATE_OPTIONS = [
    ("andaman and nicobar islands", "Andaman and Nicobar Islands"),
    ("andhra pradesh", "Andhra Pradesh"),
    ("arunachal pradesh", "Arunachal Pradesh"),
    ("assam", "Assam"),
    ("bihar", "Bihar"),
    ("chandigarh", "Chandigarh"),
    ("chhattisgarh", "Chhattisgarh"),
    (
        "dadra and nagar haveli and daman and diu",
        "Dadra and Nagar Haveli and Daman and Diu",
    ),
    ("delhi", "Delhi"),
    ("goa", "Goa"),
    ("gujarat", "Gujarat"),
    ("haryana", "Haryana"),
    ("himachal pradesh", "Himachal Pradesh"),
    ("jammu and kashmir", "Jammu and Kashmir"),
    ("jharkhand", "Jharkhand"),
    ("karnataka", "Karnataka"),
    ("kerala", "Kerala"),
    ("ladakh", "Ladakh"),
    ("lakshadweep", "Lakshadweep"),
    ("madhya pradesh", "Madhya Pradesh"),
    ("maharashtra", "Maharashtra"),
    ("manipur", "Manipur"),
    ("meghalaya", "Meghalaya"),
    ("mizoram", "Mizoram"),
    ("nagaland", "Nagaland"),
    ("odisha", "Odisha"),
    ("puducherry", "Puducherry"),
    ("punjab", "Punjab"),
    ("rajasthan", "Rajasthan"),
    ("sikkim", "Sikkim"),
    ("tamil nadu", "Tamil Nadu"),
    ("telangana", "Telangana"),
    ("tripura", "Tripura"),
    ("uttar pradesh", "Uttar Pradesh"),
    ("uttarakhand", "Uttarakhand"),
    ("west bengal", "West Bengal"),
]

REGION_OPTIONS = [
    ("north", "North"),
    ("south", "South"),
    ("east", "East"),
    ("west", "West"),
    ("central", "Central"),
    ("north_east", "North East"),
]

# Common city names returned by website forms or IP-location services.
CITY_TO_STATE = {
    "ahmedabad": "gujarat",
    "bengaluru": "karnataka",
    "bangalore": "karnataka",
    "bhopal": "madhya pradesh",
    "bhubaneswar": "odisha",
    "chandigarh": "chandigarh",
    "chennai": "tamil nadu",
    "coimbatore": "tamil nadu",
    "dehradun": "uttarakhand",
    "delhi": "delhi",
    "faridabad": "haryana",
    "ghaziabad": "uttar pradesh",
    "gurugram": "haryana",
    "gurgaon": "haryana",
    "guwahati": "assam",
    "hyderabad": "telangana",
    "indore": "madhya pradesh",
    "jaipur": "rajasthan",
    "jammu": "jammu and kashmir",
    "kanpur": "uttar pradesh",
    "kochi": "kerala",
    "kolkata": "west bengal",
    "lucknow": "uttar pradesh",
    "mumbai": "maharashtra",
    "bombay": "maharashtra",
    "nagpur": "maharashtra",
    "noida": "uttar pradesh",
    "patna": "bihar",
    "pune": "maharashtra",
    "ranchi": "jharkhand",
    "surat": "gujarat",
    "thiruvananthapuram": "kerala",
    "vadodara": "gujarat",
    "visakhapatnam": "andhra pradesh",
}


def get_region_for_location(normalized_location):
    """Return the configured Indian sales region for a state, UT or known city."""
    location = normalize_location(normalized_location)
    if not location:
        return None

    state = CITY_TO_STATE.get(location, location)

    for region_key, states in INDIA_REGIONS.items():
        if state in states:
            return region_key

    # Handles values such as "Gurugram, Haryana" or "Kolkata, West Bengal".
    for region_key, states in INDIA_REGIONS.items():
        for state_name in states:
            if re.search(rf"(^|[,\s]){re.escape(state_name)}($|[,\s])", location):
                return region_key

    return None


def assignment_candidate_keys(normalized_location):
    """
    Return assignment keys in matching order:
    exact state/location -> region -> unknown -> fallback.
    """
    location = normalize_location(normalized_location)
    keys = []

    if location:
        keys.append(location)
        region = get_region_for_location(location)
        if region:
            keys.append(f"region:{region}")
        else:
            keys.append("special:unknown")
    else:
        keys.append("special:unknown")

    keys.append("*")

    # Preserve order while removing duplicates.
    return list(dict.fromkeys(keys))


def normalize_location(value):
    value = (value or "").strip().lower()
    value = re.sub(r"\s+", " ", value)
    if value in {"", "na", "n/a", "none", "null", "not available", "unknown"}:
        return ""

    aliases = {
        "new delhi": "delhi",
        "delhi ncr": "delhi",
        "ncr": "delhi",
        "gurgaon": "gurugram",
        "bangalore": "bengaluru",
        "bombay": "mumbai",
    }
    return aliases.get(value, value)


def resolve_location(row):
    direct = normalize_location(row.get("location"))
    if direct:
        return direct, (row.get("location") or "").strip()

    ip_location = normalize_location(row.get("LocationByIPAddress"))
    return ip_location, (row.get("LocationByIPAddress") or "").strip()


def get_external_engine():
    global _EXTERNAL_ENGINE, _EXTERNAL_ENGINE_URI

    uri = current_app.config.get("LMSCOM_DB_URI")
    if not uri:
        raise RuntimeError("LMSCOM_DB_URI is not configured.")

    with _EXTERNAL_ENGINE_LOCK:
        if _EXTERNAL_ENGINE is None or _EXTERNAL_ENGINE_URI != uri:
            _EXTERNAL_ENGINE = create_engine(
                uri,
                pool_pre_ping=True,
                pool_recycle=1800,
                pool_size=5,
                max_overflow=10,
                future=True,
            )
            _EXTERNAL_ENGINE_URI = uri

    return _EXTERNAL_ENGINE


def fetch_external_leads(limit=None):
    limit = int(limit or current_app.config.get("LMSCOM_SYNC_BATCH_SIZE", 500))
    limit = max(1, min(limit, 2000))
    cutoff = current_app.config.get("LMSCOM_LEAD_CUTOFF", "2026-07-22 00:00:00")

    sql = text(f"""
        SELECT TOP ({limit})
            LeadId,
            CompanyName,
            ContactPerson,
            DesignationId,
            EmailId,
            PhoneNo,
            location,
            LeadCategory,
            UserVerticalId,
            LeadDescription,
            Status,
            IsDeleted,
            CreatedOn,
            ModifiedOn,
            AddedBy,
            ModifiedBy,
            DesignationName,
            PhoneNoCountryCode,
            AssignToUser,
            DeadRemark,
            Device,
            IPAddress,
            PageUrl,
            LocationByIPAddress,
            IsEmailSubscribed
        FROM dbo.Lead
        WHERE ISNULL(IsDeleted, 0) = 0
          AND CreatedOn >= :cutoff
        ORDER BY LeadId ASC
    """)

    with get_external_engine().connect() as connection:
        rows = connection.execute(sql, {"cutoff": cutoff}).mappings().all()

    return [dict(row) for row in rows]


def _default_status(session):
    return (
        session.query(LeadStatus)
        .filter(LeadStatus.name == "New")
        .first()
        or session.query(LeadStatus).filter(LeadStatus.is_active.is_(True)).order_by(LeadStatus.sort_order.asc()).first()
    )


def _default_source(session):
    return (
        session.query(LeadSource)
        .filter(LeadSource.name == "Website")
        .first()
        or session.query(LeadSource).filter(LeadSource.is_active.is_(True)).order_by(LeadSource.sort_order.asc()).first()
    )


def _next_lead_code(session):
    last_id = session.query(Lead.id).order_by(Lead.id.desc()).limit(1).scalar()
    return f"LD-{((last_id or 0) + 1):06d}"


def choose_assignment_rule(session, normalized_location):
    base = session.query(LeadLocationAssignmentRule).filter(
        LeadLocationAssignmentRule.is_active.is_(True)
    )

    for assignment_key in assignment_candidate_keys(normalized_location):
        rules = (
            base.filter(
                LeadLocationAssignmentRule.normalized_location == assignment_key
            )
            .order_by(
                LeadLocationAssignmentRule.last_assigned_at.asc(),
                LeadLocationAssignmentRule.assignment_count.asc(),
                LeadLocationAssignmentRule.priority.asc(),
                LeadLocationAssignmentRule.id.asc(),
            )
            .all()
        )

        if rules:
            rule = rules[0]
            rule.last_assigned_at = datetime.utcnow()
            rule.assignment_count = (rule.assignment_count or 0) + 1
            return rule

    return None



def location_matches_rule_key(normalized_location, rule_key):
    """Return True when a lead location can be handled by the supplied rule key."""
    return rule_key in assignment_candidate_keys(normalized_location)


def auto_assign_unassigned_leads(
    session=None,
    normalized_location=None,
    assigned_by_id=None,
):
    """
    Re-run automatic assignment for existing unassigned external leads.

    Matching order:
      1. Exact state/location
      2. Region
      3. Unknown location
      4. Default fallback

    When normalized_location is provided, only leads matching that newly-created
    rule are considered. This keeps rule creation fast while the manual re-run
    endpoint can process the complete unassigned queue.
    """
    session = session or db.session

    query = session.query(ExternalLeadSync).filter(
        ExternalLeadSync.assigned_user_id.is_(None)
    )

    rows = query.order_by(
        ExternalLeadSync.external_created_at.asc(),
        ExternalLeadSync.external_lead_id.asc(),
    ).all()

    result = {
        "checked": 0,
        "assigned": 0,
        "waiting_rule": 0,
        "failed": 0,
        "errors": [],
    }

    for sync_row in rows:
        if normalized_location and not location_matches_rule_key(
            sync_row.normalized_location,
            normalized_location,
        ):
            continue

        result["checked"] += 1

        try:
            rule = choose_assignment_rule(
                session,
                sync_row.normalized_location,
            )

            if not rule:
                result["waiting_rule"] += 1
                continue

            old_owner_id = sync_row.assigned_user_id
            sync_row.assigned_user_id = rule.user_id
            sync_row.assignment_rule_id = rule.id
            sync_row.assignment_mode = "AUTO"

            if sync_row.local_lead:
                sync_row.local_lead.owner_id = rule.user_id

                if assigned_by_id:
                    session.add(
                        LeadAssignmentHistory(
                            lead_id=sync_row.local_lead_id,
                            assigned_by_id=assigned_by_id,
                            old_owner_id=old_owner_id,
                            new_owner_id=rule.user_id,
                        )
                    )

            session.commit()
            result["assigned"] += 1

        except Exception as exc:
            session.rollback()
            result["failed"] += 1
            result["errors"].append(
                f"External lead {sync_row.external_lead_id}: {exc}"
            )

    return result


def sync_external_leads(session=None, limit=None):
    session = session or db.session
    rows = fetch_external_leads(limit=limit)

    result = {
        "fetched": len(rows),
        "created": 0,
        "skipped": 0,
        "failed": 0,
        "unassigned": 0,
        "auto_assigned": 0,
        "reassigned_existing": 0,
        "waiting_rule": 0,
        "errors": [],
    }

    status = _default_status(session)
    source = _default_source(session)

    for row in rows:
        external_id = row.get("LeadId")
        if external_id is None:
            result["failed"] += 1
            result["errors"].append("A row was returned without LeadId.")
            continue

        exists = session.query(ExternalLeadSync.id).filter(
            ExternalLeadSync.external_lead_id == int(external_id)
        ).first()
        if exists:
            result["skipped"] += 1
            continue

        try:
            normalized_location, source_location = resolve_location(row)
            rule = choose_assignment_rule(session, normalized_location)
            owner_id = rule.user_id if rule else None

            contact_name = (row.get("ContactPerson") or "").strip()
            company_name = (row.get("CompanyName") or "").strip()
            lead_name = contact_name or company_name or f"Website Lead {external_id}"

            description = (row.get("LeadDescription") or "").strip()
            designation = (row.get("DesignationName") or "").strip()
            page_url = (row.get("PageUrl") or "").strip()
            note_parts = []
            if description:
                note_parts.append(description)
            if designation:
                note_parts.append(f"Designation: {designation}")
            note_parts.append(f"External LMSCom Lead ID: {external_id}")
            if page_url:
                note_parts.append(f"Source page: {page_url}")

            phone_country = (row.get("PhoneNoCountryCode") or "+91").strip()
            phone = str(row.get("PhoneNo") or "").strip()
            email = (row.get("EmailId") or "").strip().lower()

            local_lead = Lead(
                lead_code=_next_lead_code(session),
                name=lead_name[:120],
                company=company_name[:120] or None,
                email=email[:120] or None,
                phone_country=phone_country[:6] or "+91",
                phone=phone[:30] or None,
                location=source_location[:500] or None,
                website=page_url[:200] or None,
                notes="\n".join(note_parts),
                owner_id=owner_id,
                status_id=status.id if status else None,
                source_id=source.id if source else None,
                lead_type="Corporate" if company_name else "Individual",
                created_at=row.get("CreatedOn") or datetime.utcnow(),
            )
            session.add(local_lead)
            session.flush()

            sync_row = ExternalLeadSync(
                external_lead_id=int(external_id),
                local_lead_id=local_lead.id,
                assigned_user_id=owner_id,
                assignment_rule_id=rule.id if rule else None,
                source_location=(row.get("location") or "")[:255] or None,
                ip_location=(row.get("LocationByIPAddress") or "")[:255] or None,
                normalized_location=normalized_location[:255] or None,
                company_name=company_name[:200] or None,
                contact_person=contact_name[:200] or None,
                email=email[:200] or None,
                phone=phone[:60] or None,
                lead_description=description,
                page_url=page_url[:500] or None,
                external_status=str(row.get("Status") or "")[:60] or None,
                assignment_mode="AUTO" if owner_id else "UNASSIGNED",
                sync_status="IMPORTED",
                external_created_at=row.get("CreatedOn"),
                synced_at=datetime.utcnow(),
            )
            session.add(sync_row)
            session.commit()

            result["created"] += 1
            if owner_id is None:
                result["unassigned"] += 1
            else:
                result["auto_assigned"] += 1

        except Exception as exc:
            session.rollback()
            result["failed"] += 1
            result["errors"].append(f"LeadId {external_id}: {exc}")

    # Revisit older unassigned rows every time a sync is run. This ensures
    # newly-created rules also take effect without re-importing the lead.
    reassignment = auto_assign_unassigned_leads(session=session)
    result["reassigned_existing"] = reassignment["assigned"]
    result["waiting_rule"] = reassignment["waiting_rule"]
    result["failed"] += reassignment["failed"]
    result["errors"].extend(reassignment["errors"])

    return result
