"""Local search started from a roster (the greedy one in this study): simulated annealing over four moves.

Moves, drawn with these probabilities:
  change        (0.3) one staff member's entry on one day becomes a different shift or a day off;
  swap          (0.3) two staff members exchange their entries on one day (cover unchanged, only who works moves);
  block change  (0.2) one staff member's entries on 2 or 3 consecutive days all become one shift, or all days off;
  block swap    (0.2) two staff members exchange their entries over 2 to 7 consecutive days.
A move is scored as its change in the study's objective plus PENALTY per unit of broken hard rule, so the search may
pass through rosters that break a rule but pays heavily for it. A worse move is accepted with probability
exp(-delta / T); T falls geometrically from T0 to T1 over a fixed number of moves. The run returns the cheapest roster
it met that breaks no rule (or, if it met none, the one with the lowest penalised score, flagged infeasible).
Deterministic for a given seed.
"""
import math
import random

from roster import OFF, staff_violations

PENALTY = 1000.0
MOVES = (("change", 0.3), ("swap", 0.3), ("block change", 0.2), ("block swap", 0.2))


def search(inst, start, w, moves, seed, t0, t1):
    rng = random.Random(seed)
    n, days, ns = inst.n, inst.days, len(inst.shift_ids)
    row = [r[:] for r in start]
    length = inst.length
    req = {k: v[0] for k, v in inst.cover.items()}
    cnt = {k: 0 for k in inst.cover}
    for r in row:
        for d, x in enumerate(r):
            if x != OFF:
                cnt[(d, x)] += 1
    minm = [s.min_minutes for s in inst.staff]

    def viol(e, r):
        return sum(u for _rule, u in staff_violations(inst, e, r))

    def ot_of(e, r):
        return max(0, sum(length[x] for x in r if x != OFF) - minm[e]) / 60

    V = [viol(e, row[e]) for e in range(n)]
    OT = [ot_of(e, row[e]) for e in range(n)]
    short_min = sum(max(0, req[k] - cnt[k]) * length[k[1]] for k in cnt)

    def score(short_m, ot, v):
        return w["W_C"] * short_m / 60 + w["W_O"] * sum(ot) + w["W_F"] * (max(ot) - min(ot)) + PENALTY * sum(v)

    cur = score(short_min, OT, V)
    best_feas = (cur, [r[:] for r in row]) if sum(V) == 0 else None
    best_any = (cur, [r[:] for r in row])
    accepted = improved = 0
    tried = {name: 0 for name, _p in MOVES}
    ratio = (t1 / t0) ** (1.0 / max(1, moves - 1))
    T = t0
    for _it in range(moves):
        u = rng.random()
        new_rows = {}
        if u < 0.3:
            kind = "change"
            e, d = rng.randrange(n), rng.randrange(days)
            old = row[e][d]
            new = rng.randrange(-1, ns)
            if new == old:
                new = OFF if old != OFF else rng.randrange(ns)
            r2 = row[e][:]
            r2[d] = new
            new_rows[e] = r2
        elif u < 0.6:
            kind = "swap"
            d, a = rng.randrange(days), rng.randrange(n)
            b = rng.randrange(n - 1)
            b = b + 1 if b >= a else b
            if row[a][d] != row[b][d]:
                ra, rb = row[a][:], row[b][:]
                ra[d], rb[d] = rb[d], ra[d]
                new_rows[a], new_rows[b] = ra, rb
        elif u < 0.8:
            kind = "block change"
            e, L = rng.randrange(n), rng.choice((2, 3))
            d = rng.randrange(days - L + 1)
            v = rng.randrange(-1, ns)
            r2 = row[e][:]
            r2[d:d + L] = [v] * L
            if r2 != row[e]:
                new_rows[e] = r2
        else:
            kind = "block swap"
            a = rng.randrange(n)
            b = rng.randrange(n - 1)
            b = b + 1 if b >= a else b
            L = rng.randint(2, 7)
            d = rng.randrange(days - L + 1)
            if row[a][d:d + L] != row[b][d:d + L]:
                ra, rb = row[a][:], row[b][:]
                ra[d:d + L], rb[d:d + L] = row[b][d:d + L], row[a][d:d + L]
                new_rows[a], new_rows[b] = ra, rb
        tried[kind] += 1
        if not new_rows:
            T *= ratio
            continue
        # cover change: only single-staff moves change how many work each shift
        dcnt = {}
        for e, r2 in new_rows.items():
            for dd in range(days):
                o, nw = row[e][dd], r2[dd]
                if o != nw:
                    if o != OFF:
                        dcnt[(dd, o)] = dcnt.get((dd, o), 0) - 1
                    if nw != OFF:
                        dcnt[(dd, nw)] = dcnt.get((dd, nw), 0) + 1
        ds = sum((max(0, req[k] - cnt[k] - c) - max(0, req[k] - cnt[k])) * length[k[1]] for k, c in dcnt.items() if c)
        ot2, V2 = OT[:], V[:]
        for e, r2 in new_rows.items():
            ot2[e], V2[e] = ot_of(e, r2), viol(e, r2)
        cand = score(short_min + ds, ot2, V2)
        delta = cand - cur
        if delta <= 0 or rng.random() < math.exp(-delta / T):
            for e, r2 in new_rows.items():
                row[e] = r2
            for k, c in dcnt.items():
                cnt[k] += c
            short_min += ds
            OT, V, cur = ot2, V2, cand
            accepted += 1
            improved += delta < 0
            if sum(V) == 0 and (best_feas is None or cur < best_feas[0] - 1e-9):
                best_feas = (cur, [r[:] for r in row])
            if cur < best_any[0] - 1e-9:
                best_any = (cur, [r[:] for r in row])
        T *= ratio
    out = best_feas[1] if best_feas else best_any[1]
    return out, {"feasible_found": best_feas is not None, "moves": moves, "accepted": accepted,
                 "improving": improved, "tried": tried}
