"""
Кабинет ОЗ и рабочее место приёмки — вычитка LOGIKA_PROSTO, волна 4б.

Поставка живёт так: сотрудник ОЗ ставит запрос из своего кабинета —
категория хранения, объём, поставщик и дата. Дата либо точная, либо
планируемая: это разделение важно. Без точной даты депо даёт только
предварительное согласование; когда ОЗ укажет точную дату, депо
согласует её отдельно — и лишь потом склад подтверждает приёмку.

Лимит поставок в день (базовые настройки) ограничивает выбор даты:
на занятый день новая поставка не согласуется.
"""

from __future__ import annotations

from datetime import date, timedelta
from typing import Any

import psycopg

ORDER_STATUS_RU = {
    "approval": "На согласовании",
    "pre_approved": "Предварительно согласовано",
    "approved": "Согласовано",
    "rejected": "Не согласовано",
    "arrival": "Запрошена приёмка",
    "received": "Принято складом",
}
#  Что считается занятым днём: согласованная, ожидаемая и принятая поставка
BUSY_STATUSES = ("approved", "arrival", "received")

WEEKDAYS_RU = ("", "понедельник", "вторник", "среда", "четверг",
               "пятница", "суббота", "воскресенье")


def has_tables(conn: psycopg.Connection) -> bool:
    """Накатана ли миграция 99 — без неё раздел открывается с пояснением."""
    with conn.cursor() as cur:
        cur.execute("SELECT to_regclass('app.supply_order') IS NOT NULL AS ok")
        return bool(cur.fetchone()["ok"])


def orders(conn: psycopg.Connection, unit_id: int | None,
           statuses: tuple[str, ...] | None = None,
           only: date | None = None) -> list[dict[str, Any]]:
    """
    Поставки депо (unit_id=None — все): новыми первыми.

    `only` — точная дата: для фильтров «сегодня/неделя/месяц» кабинета ОЗ.
    """
    if not has_tables(conn):
        return []
    where = ["1 = 1"]
    params: dict[str, Any] = {}
    if unit_id:
        where.append("o.org_unit_id = %(unit)s")
        params["unit"] = unit_id
    if statuses:
        where.append("o.status = ANY(%(st)s)")
        params["st"] = list(statuses)
    if only:
        where.append("o.exact_date = %(d)s")
        params["d"] = only
    with conn.cursor() as cur:
        cur.execute(
            f"""
            SELECT o.*, ou.name AS unit_name, ou.code AS unit_code,
                   cu.full_name AS created_by_name, cu.email AS created_by_email,
                   du.full_name AS decided_by_name,
                   ru.full_name AS received_by_name
            FROM app.supply_order o
            JOIN app.org_unit ou ON ou.id = o.org_unit_id
            LEFT JOIN app.app_user cu ON cu.id = o.created_by
            LEFT JOIN app.app_user du ON du.id = o.decided_by
            LEFT JOIN app.app_user ru ON ru.id = o.received_by
            WHERE {' AND '.join(where)}
            ORDER BY o.created_at DESC, o.id DESC
            """,
            params,
        )
        return cur.fetchall()


def busy_days(conn: psycopg.Connection, unit_id: int,
              first: date, last: date) -> dict[str, Any]:
    """
    Занятость депо по дням: сколько поставок уже стоит на каждую дату.

    Это и есть «календарь с ограничением поставок» из ТЗ: форма создания
    показывает занятость и лимит, полные дни подсвечены.
    """
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT o.exact_date AS d, count(*) AS n
            FROM app.supply_order o
            WHERE o.org_unit_id = %s
              AND o.status = ANY(%s)
              AND o.exact_date BETWEEN %s AND %s
            GROUP BY 1
            """,
            (unit_id, list(BUSY_STATUSES), first, last),
        )
        busy = {r["d"]: int(r["n"]) for r in cur.fetchall()}
        cur.execute("SELECT supply_per_day FROM app.org_unit WHERE id = %s",
                    (unit_id,))
        limit = cur.fetchone()["supply_per_day"]
    days = []
    d = first
    while d <= last:
        n = busy.get(d, 0)
        days.append({"date": d, "busy": n,
                     "limit": limit,
                     "full": limit is not None and n >= limit})
        d += timedelta(days=1)
    return {"days": days, "limit": limit}


def create_order(conn: psycopg.Connection, *, unit_id: int,
                 category: str, volume: str, supplier: str,
                 planned_date: date | None, exact_date: date | None,
                 user_id: int | None) -> int:
    """Запрос поставки из кабинета ОЗ — сразу «на согласовании»."""
    category = category.strip()
    supplier = supplier.strip()
    if not category:
        raise ValueError("Укажите категорию хранения")
    if not supplier:
        raise ValueError("Укажите поставщика")
    if not planned_date and not exact_date:
        raise ValueError(
            "Укажите дату поставки: точную или хотя бы планируемую")
    if exact_date and exact_date < date.today():
        raise ValueError("Точная дата поставки не может быть в прошлом")
    _check_day_limit(conn, unit_id, exact_date, skip_id=None)
    vol = (volume or "").strip().replace(",", ".")
    with conn.cursor() as cur:
        cur.execute(
            """
            INSERT INTO app.supply_order
                (org_unit_id, created_by, category, volume, supplier,
                 planned_date, exact_date)
            VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id
            """,
            (unit_id, user_id, category, vol or None,
             supplier, planned_date, exact_date))
        order_id = cur.fetchone()["id"]
        _log(cur, user_id, unit_id, "supply_create",
             f"Поставка №{order_id}: {category}, {supplier}")
    conn.commit()
    return order_id


def _check_day_limit(conn: psycopg.Connection, unit_id: int,
                     exact_date: date | None, skip_id: int | None) -> None:
    """День полон — новая точная дата на него не согласуется."""
    if exact_date is None:
        return
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT count(*) AS n, ou.supply_per_day AS lim
            FROM app.supply_order o
            JOIN app.org_unit ou ON ou.id = o.org_unit_id
            WHERE o.org_unit_id = %s AND o.status = ANY(%s)
              AND o.exact_date = %s AND (%s::bigint IS NULL OR o.id <> %s)
            GROUP BY ou.supply_per_day
            """,
            (unit_id, list(BUSY_STATUSES), exact_date, skip_id, skip_id))
        row = cur.fetchone()
    if row and row["lim"] is not None and int(row["n"]) >= int(row["lim"]):
        raise ValueError(
            f"На {exact_date:%d.%m.%Y} у депо уже согласовано поставок: "
            f"{int(row['n'])} из {int(row['lim'])}. Выберите другую дату")


def decide_order(conn: psycopg.Connection, order_id: int, decision: str,
                 note: str, user_id: int | None) -> dict[str, Any]:
    """
    Решение депо: согласовать, предварительно согласовать или отказать.

    С точной датой согласование окончательное; без неё — предварительное:
    поставка вернётся на согласование, когда ОЗ укажет точную дату.
    Возвращает строку поставки (нужна для письма ОЗ).
    """
    order = _order(conn, order_id)
    if order["status"] != "approval":
        raise ValueError("На согласовании этой поставки уже нет — "
                         "обновите страницу")
    status = {"approve": "approved", "pre": "pre_approved",
              "reject": "rejected"}[decision]
    if status == "approved" and not order["exact_date"]:
        status = "pre_approved"
    if status == "rejected" and not (note or "").strip():
        raise ValueError("Отказ поясните: почему депо не принимает поставку")
    if status == "approved":
        #  Согласование тоже упирается в лимит дня: создание проверяет
        #  занятость до решения депо, а здесь — уже согласованное соседями
        _check_day_limit(conn, order["org_unit_id"], order["exact_date"],
                         skip_id=order_id)
    with conn.cursor() as cur:
        cur.execute(
            """
            UPDATE app.supply_order
               SET status = %(st)s, decided_by = %(u)s, decided_at = now(),
                   decision_note = %(n)s
             WHERE id = %(id)s
            """,
            {"st": status, "u": user_id,
             "n": (note or "").strip() or None, "id": order_id})
        _log(cur, user_id, order["org_unit_id"], "supply_decide",
             f"Поставка №{order_id}: {ORDER_STATUS_RU[status]}"
             + (f" — {(note or '').strip()}" if (note or '').strip() else ""))
    conn.commit()
    return _order(conn, order_id)


def set_exact_date(conn: psycopg.Connection, order_id: int,
                   exact_date: date, user_id: int | None) -> dict[str, Any]:
    """
    ОЗ указал точную дату на предварительно согласованной поставке.

    Поставка возвращается «на согласование»: точную дату депо подтверждает
    отдельно, и лимит дня проверяется сразу.
    """
    order = _order(conn, order_id)
    if order["status"] not in ("pre_approved", "approval"):
        raise ValueError("Точную дату заполняют на предварительном "
                         "согласовании — обновите страницу")
    if exact_date < date.today():
        raise ValueError("Точная дата поставки не может быть в прошлом")
    _check_day_limit(conn, order["org_unit_id"], exact_date, skip_id=order_id)
    with conn.cursor() as cur:
        cur.execute(
            """
            UPDATE app.supply_order
               SET exact_date = %s, status = 'approval',
                   decided_by = NULL, decided_at = NULL, decision_note = NULL
             WHERE id = %s
            """, (exact_date, order_id))
        _log(cur, user_id, order["org_unit_id"], "supply_exact",
             f"Поставка №{order_id}: точная дата {exact_date:%d.%m.%Y}, "
             "снова на согласовании")
    conn.commit()
    return _order(conn, order_id)


def request_arrival(conn: psycopg.Connection, order_id: int,
                    user_id: int | None) -> dict[str, Any]:
    """ОЗ запросил приёмку: склад подтвердит получение товара."""
    order = _order(conn, order_id)
    if order["status"] != "approved":
        raise ValueError("Приёмку запрашивают по согласованной поставке")
    if order["exact_date"] and order["exact_date"] > date.today():
        raise ValueError(f"Поставка назначена на {order['exact_date']:%d.%m.%Y} — "
                         f"приёмку запрашивают в день поставки")
    with conn.cursor() as cur:
        cur.execute(
            "UPDATE app.supply_order SET status = 'arrival' WHERE id = %s",
            (order_id,))
        _log(cur, user_id, order["org_unit_id"], "supply_arrival",
             f"Поставка №{order_id}: запрошена приёмка")
    conn.commit()
    return _order(conn, order_id)


def confirm_received(conn: psycopg.Connection, order_id: int,
                     user_id: int | None) -> dict[str, Any]:
    """
    Склад подтвердил получение — финал пути поставки.

    02.10.2026: подтвердить можно в день поставки и позже — не раньше. И
    не дожидаясь отдельного запроса ОЗ: машина пришла в согласованный день —
    склад отмечает приёмку сам, письмо ОЗ уходит как раньше.
    """
    order = _order(conn, order_id)
    if order["status"] not in ("arrival", "approved"):
        raise ValueError("На приёмке этой поставки уже нет — обновите страницу")
    if order["exact_date"] and order["exact_date"] > date.today():
        raise ValueError(f"Поставка назначена на {order['exact_date']:%d.%m.%Y} — "
                         f"подтвердить приёмку можно в этот день или позже")
    with conn.cursor() as cur:
        cur.execute(
            """
            UPDATE app.supply_order
               SET status = 'received', received_by = %s, received_at = now()
             WHERE id = %s
            """, (user_id, order_id))
        _log(cur, user_id, order["org_unit_id"], "supply_received",
             f"Поставка №{order_id}: склад подтвердил приёмку")
    conn.commit()
    return _order(conn, order_id)


def _order(conn: psycopg.Connection, order_id: int) -> dict[str, Any]:
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT o.*, ou.name AS unit_name, ou.code AS unit_code,
                   cu.full_name AS created_by_name, cu.email AS created_by_email
            FROM app.supply_order o
            JOIN app.org_unit ou ON ou.id = o.org_unit_id
            LEFT JOIN app.app_user cu ON cu.id = o.created_by
            WHERE o.id = %s
            """, (order_id,))
        order = cur.fetchone()
    if not order:
        raise ValueError("Поставка не найдена — обновите страницу")
    return order


# ------------------------------------------------------------- слоты и место

def slots(conn: psycopg.Connection, unit_id: int | None = None
          ) -> list[dict[str, Any]]:
    """Слоты мелких поставщиков: в разрезе недели, всеми депо — для ОЗ."""
    if not has_tables(conn):
        return []
    where = "WHERE s.org_unit_id = %s" if unit_id else ""
    params: tuple = (unit_id,) if unit_id else ()
    with conn.cursor() as cur:
        cur.execute(
            f"""
            SELECT s.*, ou.name AS unit_name, ou.code AS unit_code
            FROM app.supply_slot s
            JOIN app.org_unit ou ON ou.id = s.org_unit_id
            {where}
            ORDER BY ou.name, s.weekday, s.time_from
            """, params)
        return cur.fetchall()


def slot_save(conn: psycopg.Connection, unit_id: int, slot_id: int | None,
              weekday: int, time_from: str, time_to: str, note: str) -> None:
    if weekday not in range(1, 8):
        raise ValueError("Выберите день недели")
    with conn.cursor() as cur:
        if slot_id:
            cur.execute(
                """
                UPDATE app.supply_slot
                   SET weekday = %s, time_from = %s, time_to = %s, note = %s
                 WHERE id = %s AND org_unit_id = %s
                """, (weekday, time_from, time_to, note.strip(), slot_id,
                      unit_id))
            if cur.rowcount == 0:
                raise ValueError("Слот не найден — обновите страницу")
        else:
            cur.execute(
                """
                INSERT INTO app.supply_slot
                    (org_unit_id, weekday, time_from, time_to, note)
                VALUES (%s, %s, %s, %s, %s)
                """, (unit_id, weekday, time_from, time_to, note.strip()))
    conn.commit()


def slot_delete(conn: psycopg.Connection, unit_id: int, slot_id: int) -> None:
    with conn.cursor() as cur:
        cur.execute(
            "DELETE FROM app.supply_slot WHERE id = %s AND org_unit_id = %s",
            (slot_id, unit_id))
        if cur.rowcount == 0:
            raise ValueError("Слот не найден — обновите страницу")
    conn.commit()


def space_of(conn: psycopg.Connection, unit_id: int | None = None
             ) -> list[dict[str, Any]]:
    """Свободное место по депо; unit_id=None — всем (кабинет ОЗ)."""
    if not has_tables(conn):
        return []
    with conn.cursor() as cur:
        if unit_id:
            cur.execute(
                """
                SELECT sp.*, ou.name AS unit_name, u.full_name AS updated_by_name
                FROM app.supply_space sp
                JOIN app.org_unit ou ON ou.id = sp.org_unit_id
                LEFT JOIN app.app_user u ON u.id = sp.updated_by
                WHERE sp.org_unit_id = %s
                """, (unit_id,))
        else:
            cur.execute(
                """
                SELECT sp.*, ou.name AS unit_name, u.full_name AS updated_by_name,
                       (SELECT max(exact_date) FROM app.supply_order o
                         WHERE o.org_unit_id = sp.org_unit_id
                           AND o.status = ANY(%s)) AS next_delivery
                FROM app.supply_space sp
                JOIN app.org_unit ou ON ou.id = sp.org_unit_id
                LEFT JOIN app.app_user u ON u.id = sp.updated_by
                ORDER BY ou.name
                """, (list(BUSY_STATUSES),))
        return cur.fetchall()


def space_update(conn: psycopg.Connection, unit_id: int, free_text: str,
                 user_id: int | None) -> None:
    """Депо обновило свободное место (пн и чт до 10:00 — задача на доске)."""
    with conn.cursor() as cur:
        cur.execute(
            """
            INSERT INTO app.supply_space (org_unit_id, free_text, updated_by)
            VALUES (%s, %s, %s)
            ON CONFLICT (org_unit_id) DO UPDATE
               SET free_text = EXCLUDED.free_text,
                   updated_by = EXCLUDED.updated_by, updated_at = now()
            """, (unit_id, free_text.strip(), user_id))
    conn.commit()


def space_fresh(conn: psycopg.Connection, unit_id: int) -> bool:
    """Обновлено ли место сегодня — по этому гаснет задача на доске."""
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT updated_at::date = current_date AS ok
            FROM app.supply_space WHERE org_unit_id = %s
            """, (unit_id,))
        row = cur.fetchone()
    return bool(row and row["ok"])


def unit_contacts(conn: psycopg.Connection) -> list[dict[str, Any]]:
    """
    Контакты администрации склада для кабинета ОЗ: начальник РЦ каждого
    депо с телефоном и рабочей почтой из его карточки.
    """
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT DISTINCT ou.id, ou.name, ou.code,
                   (e.last_name || ' ' || e.first_name ||
                    coalesce(' ' || e.middle_name, '')) AS chief_name,
                   e.phone, e.work_email
            FROM app.org_unit ou
            LEFT JOIN app.user_role ur
                   ON ur.org_unit_id = ou.id AND ur.revoked_at IS NULL
            LEFT JOIN app.role r ON r.id = ur.role_id AND r.code = 'rc_head'
            LEFT JOIN app.app_user u ON u.id = ur.user_id AND u.is_active
            LEFT JOIN app.employee e ON e.id = u.employee_id
            WHERE ou.kind = 'rc' AND ou.is_active
            ORDER BY ou.name
            """)
        return cur.fetchall()


def _log(cur, user_id, unit_id, operation: str, message: str) -> None:
    cur.execute(
        "INSERT INTO app.operation_log (user_id, operation, org_unit_id,"
        " status, rows_affected, message) VALUES (%s, %s, %s, 'ok', 1, %s)",
        (user_id, operation, unit_id, message[:500]))
