import { z } from 'zod';
import type { AgentStatus, HumanStatus, Pose } from '@pixeloffice/protocol';
import { DurationSchema as Duration } from './duration.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { parseYamlWith } from './yaml.ts';

export type RuleTarget =
  | { kind: 'own_seat' | 'owner_pod_seat' | 'meeting_room' | 'meeting_room_standing' | 'current_work_seat' | 'stay' | 'exit' }
  | { kind: 'zone'; zoneId: string; pose?: Pose; tag?: string };
export type Rules = {
  dwellMs: { agent: number; human: number };
  busWaitMs: number; // сколько ждущий стоит на остановке до вызова автобуса (спека транспорта 3.6)
  human: Record<HumanStatus, RuleTarget[]>;
  agent: Record<AgentStatus, RuleTarget[]>;
};

const SIMPLE = new Set(['own_seat', 'owner_pod_seat', 'meeting_room', 'meeting_room_standing', 'current_work_seat', 'stay', 'exit']);
const POSES = new Set(['sit', 'stand', 'play']);
// id зоны может содержать «:» (`pod:stas`, `meeting:m1`, спека 5.1), поэтому id разбирается лениво до необязательного суффикса.
const ZONE_RE = /^zone:([^=]+?)(?::(pose|tag)=([^:=]+))?$/;

export function parseTarget(s: string): RuleTarget | null {
  if (SIMPLE.has(s)) return { kind: s } as RuleTarget;
  const m = ZONE_RE.exec(s);
  if (!m) return null;
  const zoneId = m[1]!;
  if (!m[2]) return { kind: 'zone', zoneId };
  if (m[2] === 'pose') return POSES.has(m[3]!) ? { kind: 'zone', zoneId, pose: m[3] as Pose } : null;
  return { kind: 'zone', zoneId, tag: m[3]! };
}

const List = z.array(z.string()).min(1);
// idle и needs_input человека — опциональные (спека 17.11.2026): нет ключа — ведёт себя как online,
// чтобы развёрнутые офисы со старым rules.yaml не ломались.
const RulesFileSchema = z.strictObject({
  dwell: z.strictObject({ agent: Duration, human: Duration }).default({ agent: 20_000, human: 60_000 }),
  bus: z.strictObject({ wait: Duration }).default({ wait: 60_000 }),
  human: z.strictObject({ online: List, meeting: List, offline: List, idle: List.optional(), needs_input: List.optional() }),
  agent: z.strictObject({ working: List, idle: List, needs_input: List, offline: List }),
});

export function parseRules(text: string, file = 'rules.yaml', zoneIds?: ReadonlySet<string>): Result<Rules> {
  const r = parseYamlWith(file, text, RulesFileSchema);
  if (!r.ok) return r;
  const errors: MapError[] = [];
  // Источник частичный: у человека idle и needs_input необязательны (спека 17.11.2026), идём по существующим ключам.
  const convert = <K extends string>(group: 'human' | 'agent', src: Partial<Record<K, string[]>>): Record<K, RuleTarget[]> => {
    const out = {} as Record<K, RuleTarget[]>;
    for (const key of Object.keys(src) as K[]) {
      out[key] = (src[key] ?? []).flatMap((s, i) => {
        const t = parseTarget(s);
        if (!t) {
          errors.push({ file, code: 'unknown_target', message: `${group}.${key}[${i}]: неизвестная цель «${s}»` });
          return [];
        }
        if (t.kind === 'zone' && zoneIds && !zoneIds.has(t.zoneId)) {
          errors.push({ file, code: 'unknown_zone', message: `${group}.${key}[${i}]: зоны «${t.zoneId}» нет в office.yaml` });
        }
        return [t];
      });
    }
    return out;
  };
  const human = convert('human', r.value.human);
  const agent = convert('agent', r.value.agent);
  human.idle ??= human.online; // спека 17.11.2026: не задан — как online
  human.needs_input ??= human.online;
  if (errors.length) return fail(errors);
  return ok({ dwellMs: r.value.dwell, busWaitMs: r.value.bus.wait, human, agent });
}
