from __future__ import annotations

import os
from datetime import date, datetime, time, timedelta
from html import escape

from flask import current_app
from flask_mail import Message

from InvestmentManager.crm_clients_store import (
    create_client,
    create_client_meeting,
    list_agent_calendar_meetings,
)
from modules.core.agent_schedule import read_schedule_events
from modules.core.error_responses import log_internal_error
from modules.core.extensions import mail
from InvestmentWebsite.offers.lead_spam_guard import validate_lead_limits
from InvestmentWebsite.offers.platform_facade import EMAIL_REGEX
from modules.core.json_store import JsonStoreError
from InvestmentWebsite.services.catalog import get_agent_email

WEEKDAY_LABELS = [
    "Poniedziałek",
    "Wtorek",
    "Środa",
    "Czwartek",
    "Piątek",
    "Sobota",
    "Niedziela",
]

FRANCHISE_OFFICE_NOTIFICATION_EMAIL = "biuroinvestmentkk@gmail.com"


def _agent_id() -> int:
    return int(current_app.config.get("FRANCHISE_MEETING_AGENT_ID", 101) or 101)


def _slot_minutes() -> int:
    value = int(current_app.config.get("FRANCHISE_MEETING_SLOT_MINUTES", 60) or 60)
    return value if value > 0 else 60


def _window_days() -> int:
    value = int(current_app.config.get("FRANCHISE_MEETING_WINDOW_DAYS", 21) or 21)
    return value if value > 0 else 21


def _workday_start_hour() -> int:
    value = int(current_app.config.get("FRANCHISE_MEETING_WORKDAY_START_HOUR", 9) or 9)
    return min(max(value, 0), 23)


def _workday_end_hour() -> int:
    value = int(current_app.config.get("FRANCHISE_MEETING_WORKDAY_END_HOUR", 17) or 17)
    return min(max(value, 1), 24)


def _parse_datetime(value: str | None) -> datetime | None:
    if not value:
        return None

    text = str(value).strip()
    if not text:
        return None

    for parser in (datetime.fromisoformat,):
        try:
            return parser(text)
        except ValueError:
            continue

    if len(text) == 10:
        try:
            return datetime.combine(date.fromisoformat(text), time.min)
        except ValueError:
            return None
    return None


def _normalize_source(raw_source: str | None) -> tuple[str, str]:
    source = (raw_source or "").strip().lower()
    if source in {"lexpress", "l-express", "lexpress-franchise", "lexpress_franchise"}:
        return "lexpress", "Lexpress Franchise"
    return "franczyza", "Formularz franczyza"


def _load_manual_schedule_events(agent_id: int) -> list[dict]:
    # The CRM owns the calendar file; the read contract (missing file -> [], damaged file -> JsonStoreCorrupt) is modules.core.agent_schedule.
    return read_schedule_events(agent_id)


def _iter_busy_intervals(agent_id: int) -> list[tuple[datetime, datetime]]:
    slot_minutes = _slot_minutes()
    intervals: list[tuple[datetime, datetime]] = []

    for event in _load_manual_schedule_events(agent_id):
        start_raw = event.get("start")
        end_raw = event.get("end")
        start_dt = _parse_datetime(start_raw)
        if not start_dt:
            continue

        if isinstance(start_raw, str) and len(start_raw.strip()) == 10 and not end_raw:
            end_dt = datetime.combine(start_dt.date() + timedelta(days=1), time.min)
        else:
            end_dt = _parse_datetime(end_raw) or (start_dt + timedelta(minutes=slot_minutes))

        if end_dt > start_dt:
            intervals.append((start_dt, end_dt))

    for meeting in list_agent_calendar_meetings(agent_id):
        if str(meeting.get("meeting_status") or "").strip().lower() == "cancelled":
            continue

        start_dt = _parse_datetime(meeting.get("start_at"))
        if not start_dt:
            continue

        end_dt = _parse_datetime(meeting.get("end_at")) or (start_dt + timedelta(minutes=slot_minutes))
        if end_dt > start_dt:
            intervals.append((start_dt, end_dt))

    return intervals


def _slot_overlaps_busy_time(start_at: datetime, end_at: datetime, busy_intervals: list[tuple[datetime, datetime]]) -> bool:
    for busy_start, busy_end in busy_intervals:
        if start_at < busy_end and end_at > busy_start:
            return True
    return False


def get_public_franchise_availability() -> dict:
    agent_id = _agent_id()
    slot_minutes = _slot_minutes()
    window_days = _window_days()
    workday_start = _workday_start_hour()
    workday_end = _workday_end_hour()
    now = datetime.now()
    try:
        busy_intervals = _iter_busy_intervals(agent_id)
    except (JsonStoreError, OSError) as exc:
        # Fail closed: an unreadable calendar is NOT an empty one. Offer no time (and book none, see book_public_franchise_meeting); the file
        # is left untouched and no detail reaches the visitor - the cause is logged with a request id.
        log_internal_error("franchise.calendar_unreadable (no slots are offered)", exc)
        busy_intervals = None

    days = []
    for day_offset in (range(window_days) if busy_intervals is not None else ()):
        current_day = date.today() + timedelta(days=day_offset)
        if current_day.weekday() >= 5:
            continue

        slots = []
        current_start = datetime.combine(current_day, time(hour=workday_start))
        last_end = datetime.combine(current_day, time(hour=workday_end))

        while current_start + timedelta(minutes=slot_minutes) <= last_end:
            current_end = current_start + timedelta(minutes=slot_minutes)
            if current_start > now and not _slot_overlaps_busy_time(current_start, current_end, busy_intervals):
                slots.append(
                    {
                        "start_at": current_start.isoformat(timespec="minutes"),
                        "end_at": current_end.isoformat(timespec="minutes"),
                        "label": current_start.strftime("%H:%M"),
                    }
                )
            current_start += timedelta(minutes=slot_minutes)

        if slots:
            days.append(
                {
                    "date": current_day.isoformat(),
                    "label": current_day.strftime("%d.%m.%Y"),
                    "weekday_label": WEEKDAY_LABELS[current_day.weekday()],
                    "slots": slots,
                }
            )

    return {
        "agent_id": agent_id,
        "slot_minutes": slot_minutes,
        "days": days,
        "source_options": [
            {"value": "franczyza", "label": "Formularz franczyza"},
            {"value": "lexpress", "label": "Lexpress Franchise"},
        ],
    }


def _build_notification_recipients(agent_id: int) -> list[str]:
    recipients = []
    agent_email = get_agent_email(agent_id)
    if agent_email:
        recipients.append(agent_email)

    primary = os.getenv("MAIL_USERNAME")
    if primary:
        recipients.append(primary)

    extra = os.getenv("PLATFORM_EXTRA_RECIPIENT")
    if extra:
        recipients.append(extra)

    recipients.append(FRANCHISE_OFFICE_NOTIFICATION_EMAIL)

    unique = []
    seen = set()
    for item in recipients:
        normalized = str(item or "").strip().lower()
        if not normalized or normalized in seen:
            continue
        seen.add(normalized)
        unique.append(str(item).strip())
    return unique


def _send_franchise_meeting_email(*, agent_id: int, client: dict, meeting: dict, source_label: str, note: str) -> None:
    recipients = _build_notification_recipients(agent_id)
    if not recipients:
        raise ValueError("Brak odbiorców powiadomienia e-mail.")

    full_name = f"{client.get('first_name', '')} {client.get('last_name', '')}".strip()
    start_at = meeting.get("start_at") or ""
    subject = f"Nowe spotkanie franczyzowe - {full_name or 'Nowy kontakt'}"
    body = (
        "Nowe spotkanie franczyzowe zostało umówione.\n\n"
        f"Agent ID: {agent_id}\n"
        f"Imię i nazwisko: {full_name or '-'}\n"
        f"Telefon: {client.get('phone') or '-'}\n"
        f"E-mail: {client.get('email') or '-'}\n"
        f"Termin: {start_at or '-'}\n"
        f"Źródło: {source_label}\n"
        f"Notatka: {note or '-'}\n"
    )
    html = (
        "<div style='font-family:Arial,sans-serif;color:#0f172a'>"
        "<h2>Nowe spotkanie franczyzowe</h2>"
        f"<p><strong>Imię i nazwisko:</strong> {escape(full_name or '-')}</p>"
        f"<p><strong>Telefon:</strong> {escape(client.get('phone') or '-')}</p>"
        f"<p><strong>E-mail:</strong> {escape(client.get('email') or '-')}</p>"
        f"<p><strong>Termin:</strong> {escape(start_at or '-')}</p>"
        f"<p><strong>Źródło:</strong> {escape(source_label)}</p>"
        f"<p><strong>Notatka:</strong> {escape(note or '-')}</p>"
        "</div>"
    )
    reply_to = (client.get("email") or "").strip() or None
    msg = Message(subject=subject, recipients=recipients, body=body, html=html, reply_to=reply_to)
    mail.send(msg)


def book_public_franchise_meeting(payload: dict) -> tuple[dict, int]:
    limits = {"first_name": 100, "last_name": 100, "phone": 32, "email": 254, "city": 120, "source": 50, "start_at": 40}
    if any(not isinstance(payload.get(key, ""), str) or len(payload.get(key, "")) > size for key, size in limits.items()):
        return {"success": False, "error": "Nieprawidłowe dane formularza."}, 400
    first_name = str(payload.get("first_name") or "").strip()
    last_name = str(payload.get("last_name") or "").strip()
    phone = str(payload.get("phone") or "").strip()
    email = str(payload.get("email") or "").strip()
    city = str(payload.get("city") or "").strip()
    source_key, source_label = _normalize_source(payload.get("source"))
    start_at = str(payload.get("start_at") or "").strip()

    if not first_name or not last_name:
        return {"success": False, "error": "Imię i nazwisko są wymagane."}, 400
    if not phone and not email:
        return {"success": False, "error": "Podaj telefon lub e-mail."}, 400
    if not start_at:
        return {"success": False, "error": "Wybierz termin spotkania."}, 400
    _, phone_error = validate_lead_limits({"phone": phone, "email": email, "message": ""})
    if phone_error or (email and (not EMAIL_REGEX.fullmatch(email) or any(ch.isspace() for ch in email))):
        return {"success": False, "error": phone_error or "Nieprawidłowy e-mail."}, 400

    chosen_start = _parse_datetime(start_at)
    if not chosen_start:
        return {"success": False, "error": "Nieprawidłowy termin spotkania."}, 400

    chosen_end = chosen_start + timedelta(minutes=_slot_minutes())
    availability = get_public_franchise_availability()
    allowed_starts = {
        slot["start_at"]
        for day in availability["days"]
        for slot in day["slots"]
    }
    if start_at not in allowed_starts:
        return {"success": False, "error": "Wybrany termin nie jest już dostępny."}, 409

    notes = f"Publiczny booking spotkania franczyzowego. Źródło: {source_label}."

    agent_id = _agent_id()
    client_payload = {
        "first_name": first_name,
        "last_name": last_name,
        "email": email,
        "phone": phone,
        "city": city,
        "source_label": source_label,
        "notes": notes,
        "status_code": "meeting_planned",
        "client_type": "franchise",
        "last_contact_at": datetime.now().isoformat(timespec="minutes"),
        "next_action_at": start_at,
    }
    client, _duplicates = create_client(
        client_payload,
        owner_agent_id=agent_id,
        created_by_user_id=agent_id,
        force_create=True,
    )
    if not client:
        return {"success": False, "error": "Nie udało się zapisać kontaktu."}, 500

    meeting = create_client_meeting(
        int(client["id"]),
        {
            "meeting_type": "consultation",
            "meeting_status": "planned",
            "start_at": chosen_start.isoformat(timespec="minutes"),
            "end_at": chosen_end.isoformat(timespec="minutes"),
            "location_label": "Spotkanie franczyzowe",
            "notes": notes,
        },
        actor_user_id=agent_id,
    )
    if not meeting:
        return {"success": False, "error": "Nie udało się utworzyć spotkania."}, 500

    email_sent = True
    try:
        _send_franchise_meeting_email(
            agent_id=agent_id,
            client=client,
            meeting=meeting,
            source_label=source_label,
            note=notes,
        )
    except Exception as exc:
        email_sent = False
        current_app.logger.error("Franchise meeting email error (%s)", type(exc).__name__)

    return {
        "success": True,
        "client_id": int(client["id"]),
        "meeting_id": int(meeting["id"]),
        "source": source_key,
        "source_label": source_label,
        "start_at": meeting.get("start_at"),
        "email_sent": email_sent,
    }, 200
