from __future__ import annotations

import itertools
import time
from typing import Dict, List, Optional, Sequence, Tuple

NURSES: Tuple[str, ...] = tuple(f"N{i:02d}" for i in range(1, 11))
SENIORS: frozenset = frozenset(f"N{i:02d}" for i in range(1, 6))
JUNIORS: frozenset = frozenset(f"N{i:02d}" for i in range(6, 11))

NUM_NURSES: int = 10
NUM_DAYS: int = 14
WEEKENDS: frozenset = frozenset({5, 6, 12, 13})
SHIFTS: Tuple[str, ...] = ("D", "E", "N", "O")
WORK_SHIFTS: frozenset = frozenset({"D", "E", "N"})

VACATIONS: Dict[str, frozenset] = {
    "N01": frozenset({2, 3}),
    "N03": frozenset({10}),
    "N05": frozenset({5, 6}),
    "N08": frozenset({0, 1}),
    "N10": frozenset({12, 13}),
}

FORBIDDEN_TRANSITIONS: frozenset = frozenset({
    ("N", "D"),
    ("N", "E"),
    ("E", "D"),
})


def validate_schedule(schedule: Dict[str, Sequence[str]]) -> Tuple[bool, List[str]]:
    """Validate a 14-day schedule for 10 nurses against all 7 constraints.

    Returns (is_valid, errors).
    """
    errors: List[str] = []

    if set(schedule.keys()) != set(NURSES):
        errors.append(f"간호사 키 불일치: expected {NURSES}, got {sorted(schedule.keys())}")
        return False, errors

    for n in NURSES:
        row = schedule[n]
        if len(row) != NUM_DAYS:
            errors.append(f"{n}: 근무일 길이 오류 ({len(row)} != {NUM_DAYS})")
            return False, errors
        for d, s in enumerate(row):
            if s not in SHIFTS:
                errors.append(f"{n} Day {d}: 유효하지 않은 근무 코드 '{s}'")
                return False, errors

    # Constraint 1 & 2: Daily shift counts & >=1 senior per working shift
    for d in range(NUM_DAYS):
        by_shift: Dict[str, List[str]] = {"D": [], "E": [], "N": [], "O": []}
        for n in NURSES:
            by_shift[schedule[n][d]].append(n)

        if (
            len(by_shift["D"]) != 2
            or len(by_shift["E"]) != 2
            or len(by_shift["N"]) != 2
            or len(by_shift["O"]) != 4
        ):
            errors.append(
                f"제약1 위반 (Day {d}): D={len(by_shift['D'])}, E={len(by_shift['E'])}, "
                f"N={len(by_shift['N'])}, O={len(by_shift['O'])}"
            )

        for sh in ("D", "E", "N"):
            if not any(n in SENIORS for n in by_shift[sh]):
                errors.append(f"제약2 위반 (Day {d}, {sh}조): 시니어 미포함 ({by_shift[sh]})")

    # Constraint 3, 4, 5, 6: Per-nurse sequential & vacation constraints
    work_counts: Dict[str, int] = {}
    n_counts: Dict[str, int] = {}
    wk_counts: Dict[str, int] = {}

    for n in NURSES:
        row = schedule[n]

        # Constraint 6: Vacations
        for vac_d in VACATIONS.get(n, frozenset()):
            if row[vac_d] != "O":
                errors.append(f"제약6 위반 ({n} Day {vac_d}): 사전 휴가 미준수 ('{row[vac_d]}')")

        # Constraint 3: Forbidden transitions
        for d in range(NUM_DAYS - 1):
            if (row[d], row[d + 1]) in FORBIDDEN_TRANSITIONS:
                errors.append(f"제약3 위반 ({n} Day {d}->{d+1}): 금지 전환 {row[d]}->{row[d+1]}")

        # Constraint 4: Max 5 consecutive working days
        consec_work = 0
        for d in range(NUM_DAYS):
            if row[d] != "O":
                consec_work += 1
                if consec_work > 5:
                    errors.append(f"제약4 위반 ({n} Day {d}): 6일 이상 연속 근무")
            else:
                consec_work = 0

        # Constraint 5: Max 2 consecutive N shifts
        consec_n = 0
        for d in range(NUM_DAYS):
            if row[d] == "N":
                consec_n += 1
                if consec_n > 2:
                    errors.append(f"제약5 위반 ({n} Day {d}): 3일 이상 연속 야간(N)")
            else:
                consec_n = 0

        work_counts[n] = sum(1 for s in row if s != "O")
        n_counts[n] = sum(1 for s in row if s == "N")
        wk_counts[n] = sum(1 for d in WEEKENDS if row[d] != "O")

    # Constraint 7: Fairness
    for n, wc in work_counts.items():
        if not (7 <= wc <= 10):
            errors.append(f"제약7 위반 ({n}): 총 근무일수 {wc} (허용 7~10)")

    n_diff = max(n_counts.values()) - min(n_counts.values())
    if n_diff > 2:
        errors.append(
            f"제약7 위반 (야간 공정성): max-min={n_diff} > 2 "
            f"(min={min(n_counts.values())}, max={max(n_counts.values())})"
        )

    wk_diff = max(wk_counts.values()) - min(wk_counts.values())
    if wk_diff > 2:
        errors.append(
            f"제약7 위반 (주말 공정성): max-min={wk_diff} > 2 "
            f"(min={min(wk_counts.values())}, max={max(wk_counts.values())})"
        )

    return len(errors) == 0, errors


def _solve_with_bounds(
    n_min: int,
    n_max: int,
    wk_min: int,
    wk_max: int,
    max_nodes: int = 200_000,
) -> Optional[Dict[str, List[str]]]:
    """Day-by-day backtracking CSP solver with forward checking and fairness heuristics."""
    is_senior = [n in SENIORS for n in NURSES]
    vac_flags = [[d in VACATIONS.get(n, frozenset()) for d in range(NUM_DAYS)] for n in NURSES]
    is_wk = [d in WEEKENDS for d in range(NUM_DAYS)]

    # Precompute remaining non-vacation days (total & weekend) from day d..13 inclusive
    rem_non_vac = [[0] * (NUM_DAYS + 1) for _ in range(NUM_NURSES)]
    rem_wk_non_vac = [[0] * (NUM_DAYS + 1) for _ in range(NUM_NURSES)]
    for i in range(NUM_NURSES):
        for d in range(NUM_DAYS - 1, -1, -1):
            avail = 0 if vac_flags[i][d] else 1
            rem_non_vac[i][d] = rem_non_vac[i][d + 1] + avail
            rem_wk_non_vac[i][d] = rem_wk_non_vac[i][d + 1] + (avail if is_wk[d] else 0)

    # Mutable search state
    grid: List[List[str]] = [[""] * NUM_DAYS for _ in range(NUM_NURSES)]
    work_cnt = [0] * NUM_NURSES
    n_cnt = [0] * NUM_NURSES
    wk_cnt = [0] * NUM_NURSES
    consec_work = [0] * NUM_NURSES
    consec_n = [0] * NUM_NURSES
    prev_shift: List[Optional[str]] = [None] * NUM_NURSES

    nodes = 0

    def valid_pairs_with_senior(candidates: List[int]) -> List[Tuple[int, int]]:
        pairs: List[Tuple[int, int]] = []
        for a, b in itertools.combinations(candidates, 2):
            if is_senior[a] or is_senior[b]:
                pairs.append((a, b))
        return pairs

    def backtrack(d: int) -> bool:
        nonlocal nodes
        if d == NUM_DAYS:
            return True

        nodes += 1
        if nodes > max_nodes:
            return False

        # Forward-check per-nurse bounds before branching
        rem_d = NUM_DAYS - d
        for i in range(NUM_NURSES):
            if work_cnt[i] > 10 or work_cnt[i] + rem_non_vac[i][d] < 7:
                return False
            if n_cnt[i] > n_max or n_cnt[i] + rem_non_vac[i][d] < n_min:
                return False
            if wk_cnt[i] > wk_max or wk_cnt[i] + rem_wk_non_vac[i][d] < wk_min:
                return False
            # Also cap max additional N due to max-2-consecutive-N rule: roughly ceil(2/3 * rem_d) + 1
            if n_cnt[i] + ((rem_d * 2) // 3 + 2) < n_min:
                return False

        # Determine eligible nurses for each working shift on day d
        cand_d: List[int] = []
        cand_e: List[int] = []
        cand_n: List[int] = []

        wk_today = is_wk[d]
        for i in range(NUM_NURSES):
            if vac_flags[i][d]:
                continue
            if consec_work[i] >= 5:
                continue
            if work_cnt[i] >= 10:
                continue
            if wk_today and wk_cnt[i] >= wk_max:
                continue

            ps = prev_shift[i]
            if ps == "N":
                if consec_n[i] < 2 and n_cnt[i] < n_max:
                    cand_n.append(i)
            elif ps == "E":
                cand_e.append(i)
                if n_cnt[i] < n_max:
                    cand_n.append(i)
            else:
                cand_d.append(i)
                cand_e.append(i)
                if n_cnt[i] < n_max:
                    cand_n.append(i)

        if len(cand_d) < 2 or len(cand_e) < 2 or len(cand_n) < 2:
            return False

        # Heuristic ordering: prioritize nurses with lower current counts (fairness-first)
        def n_priority(i: int) -> Tuple[int, int, int]:
            # Nurses who urgently need N or weekend shifts come first
            wk_need = (wk_min - wk_cnt[i]) if wk_today else 0
            return (n_cnt[i], -wk_need, work_cnt[i])

        def work_priority(i: int) -> Tuple[int, int]:
            wk_need = (wk_min - wk_cnt[i]) if wk_today else 0
            return (-wk_need, work_cnt[i])

        cand_n.sort(key=n_priority)
        cand_d.sort(key=work_priority)
        cand_e.sort(key=work_priority)

        n_pairs = valid_pairs_with_senior(cand_n)
        if not n_pairs:
            return False

        # Precompute day d+1 lookahead helper
        has_next = d + 1 < NUM_DAYS

        for n1, n2 in n_pairs:
            # Build D pairs excluding {n1, n2}
            rem_d_cands = [i for i in cand_d if i != n1 and i != n2]
            if len(rem_d_cands) < 2:
                continue
            d_pairs = valid_pairs_with_senior(rem_d_cands)
            if not d_pairs:
                continue

            for d1, d2 in d_pairs:
                rem_e_cands = [i for i in cand_e if i not in (n1, n2, d1, d2)]
                if len(rem_e_cands) < 2:
                    continue
                e_pairs = valid_pairs_with_senior(rem_e_cands)
                if not e_pairs:
                    continue

                for e1, e2 in e_pairs:
                    # 1-day lookahead for day d+1:
                    # Ensure enough nurses (incl. >=1 senior) can take D on day d+1
                    if has_next:
                        next_d_total = 0
                        next_d_seniors = 0
                        next_e_total = 0
                        next_e_seniors = 0
                        for i in range(NUM_NURSES):
                            if vac_flags[i][d + 1]:
                                continue
                            if i in (n1, n2):
                                # Doing N today -> cannot do D or E tomorrow
                                continue
                            if i in (e1, e2):
                                # Doing E today -> can do E tomorrow if consec_work+1 < 5
                                if consec_work[i] + 1 < 5 and work_cnt[i] + 1 < 10:
                                    next_e_total += 1
                                    if is_senior[i]:
                                        next_e_seniors += 1
                            elif i in (d1, d2):
                                if consec_work[i] + 1 < 5 and work_cnt[i] + 1 < 10:
                                    next_d_total += 1
                                    next_e_total += 1
                                    if is_senior[i]:
                                        next_d_seniors += 1
                                        next_e_seniors += 1
                            else:
                                # Doing O today -> consec_work resets to 0
                                if work_cnt[i] < 10:
                                    next_d_total += 1
                                    next_e_total += 1
                                    if is_senior[i]:
                                        next_d_seniors += 1
                                        next_e_seniors += 1
                        if (
                            next_d_total < 2
                            or next_d_seniors < 1
                            or next_e_total < 2
                            or next_e_seniors < 1
                        ):
                            continue

                    # Save state & apply day d assignment
                    saved_cw = consec_work[:]
                    saved_cn = consec_n[:]
                    saved_prev = prev_shift[:]

                    for i in range(NUM_NURSES):
                        if i == d1 or i == d2:
                            sh = "D"
                        elif i == e1 or i == e2:
                            sh = "E"
                        elif i == n1 or i == n2:
                            sh = "N"
                        else:
                            sh = "O"
                        grid[i][d] = sh
                        prev_shift[i] = sh
                        if sh == "O":
                            consec_work[i] = 0
                            consec_n[i] = 0
                        else:
                            work_cnt[i] += 1
                            consec_work[i] += 1
                            if wk_today:
                                wk_cnt[i] += 1
                            if sh == "N":
                                n_cnt[i] += 1
                                consec_n[i] += 1
                            else:
                                consec_n[i] = 0

                    if backtrack(d + 1):
                        return True

                    # Undo day d assignment
                    for i in range(NUM_NURSES):
                        sh = grid[i][d]
                        if sh != "O":
                            work_cnt[i] -= 1
                            if wk_today:
                                wk_cnt[i] -= 1
                            if sh == "N":
                                n_cnt[i] -= 1
                    consec_work[:] = saved_cw
                    consec_n[:] = saved_cn
                    prev_shift[:] = saved_prev

        return False

    if backtrack(0):
        return {NURSES[i]: grid[i] for i in range(NUM_NURSES)}
    return None


def solve() -> Dict[str, List[str]]:
    """Solve the 10-nurse, 14-day 3-shift scheduling problem.

    Returns a dict mapping 'N01'..'N10' to a list of 14 shift codes ('D','E','N','O').
    """
    # Try strictest fairness bounds first (spread <= 1), then relax up to spread <= 2
    bound_tiers = [
        (2, 3, 2, 3),  # Ultra-fair: N in [2,3], Weekend in [2,3] (diff <= 1)
        (2, 4, 1, 3),  # Fair: N in [2,4], Weekend in [1,3] (diff <= 2)
        (1, 3, 1, 3),
        (2, 4, 2, 4),
    ]
    for n_min, n_max, wk_min, wk_max in bound_tiers:
        res = _solve_with_bounds(n_min, n_max, wk_min, wk_max)
        if res is not None:
            ok, errs = validate_schedule(res)
            if ok:
                return res
            raise RuntimeError(f"내부 검증 실패: {errs}")

    raise RuntimeError("주어진 제약 조건을 만족하는 근무표를 찾지 못했습니다.")


def format_schedule(schedule: Dict[str, Sequence[str]]) -> str:
    """Format the 14-day schedule into a readable table with summary stats."""
    lines: List[str] = []
    header = "간호사(등급) | " + " ".join(
        f"{d:02d}{'*' if d in WEEKENDS else ' '}" for d in range(NUM_DAYS)
    ) + " | 근무  N  주말"
    sep = "-" * len(header)
    lines.append(header)
    lines.append(sep)

    for n in NURSES:
        role = "SR" if n in SENIORS else "JR"
        row = schedule[n]
        shifts_str = " ".join(f" {s} " for s in row)
        wc = sum(1 for s in row if s != "O")
        nc = sum(1 for s in row if s == "N")
        wkc = sum(1 for d in WEEKENDS if row[d] != "O")
        lines.append(f"  {n} ({role})  | {shifts_str} |  {wc:2d}  {nc:2d}   {wkc:2d}")

    lines.append(sep)
    lines.append("* 표시된 날짜(05, 06, 12, 13)는 주말입니다.")
    return "\n".join(lines)


if __name__ == "__main__":
    t0 = time.perf_counter()
    result = solve()
    elapsed = time.perf_counter() - t0
    ok, errors = validate_schedule(result)
    print(format_schedule(result))
    print(f"\n풀이 시간: {elapsed * 1000:.2f} ms | 제약 검증: {'ALL PASS' if ok else f'FAIL ({errors})'}")
