/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { ALL_PROFILES } from '../profiles/index.js';
import { listTasks } from './task-state.js';
import { listWorkflowRuns } from './workflow-state.js';
import { PHASE_TO_PROFILE } from './workflow-instructions.js';
export function resolveRoleActivation(cwd, projectProfiles) {
    const activeRun = findActiveRun(cwd);
    if (!activeRun) {
        // Even without a running workflow, consider task owner roles for badge activation
        const ownerRoles = resolveTaskOwnerRoles(cwd, projectProfiles);
        return { projectRoles: projectProfiles, activeRoles: ownerRoles, interactions: [], taskId: null, runId: null };
    }
    const activeTask = findActiveTask(cwd, activeRun.storyId);
    const taskRoles = activeTask?.roles;
    const activeRoles = resolveActiveRoles(projectProfiles, taskRoles, activeRun);
    const interactions = resolveInteractions(activeRun);
    return {
        projectRoles: projectProfiles,
        activeRoles,
        interactions,
        taskId: activeRun.storyId,
        runId: activeRun.id,
    };
}
export function validateRolesExist(roleIds) {
    const allIds = new Set(ALL_PROFILES.map((p) => p.id));
    const valid = [];
    const invalid = [];
    for (const id of roleIds) {
        if (allIds.has(id)) {
            valid.push(id);
        }
        else {
            invalid.push(id);
        }
    }
    return { valid, invalid };
}
export function expandedProfiles(configProfiles, taskRoles) {
    if (!taskRoles)
        return configProfiles;
    const expanded = new Set(configProfiles);
    const allIds = new Set(ALL_PROFILES.map((p) => p.id));
    for (const role of [...taskRoles.required, ...taskRoles.optional]) {
        if (allIds.has(role)) {
            expanded.add(role);
        }
    }
    return [...expanded];
}
/**
 * When no workflow run is active, resolve roles from task owner fields.
 * This ensures the role badge activates immediately on task creation.
 */
function resolveTaskOwnerRoles(cwd, projectProfiles) {
    const tasks = listTasks(cwd);
    const activeTasks = tasks.filter((t) => t.status === 'open' || t.status === 'claimed');
    if (activeTasks.length === 0)
        return [];
    const active = new Set();
    for (const task of activeTasks) {
        if (task.owner) {
            // owner is formatted as "setup-agents:<profileId>"
            const profileId = task.owner.replace('setup-agents:', '');
            if (projectProfiles.includes(profileId) || ALL_PROFILES.some((p) => p.id === profileId)) {
                active.add(profileId);
            }
        }
    }
    return [...active];
}
function findActiveRun(cwd) {
    const runs = listWorkflowRuns(cwd);
    return runs.find((r) => r.status === 'running') ?? runs.find((r) => r.status === 'paused');
}
function findActiveTask(cwd, storyId) {
    const tasks = listTasks(cwd);
    return tasks.find((t) => t.id === storyId);
}
function resolveActiveRoles(projectProfiles, taskRoles, run) {
    const active = new Set();
    // Roles from running/blocked phases
    for (const phase of run.phases) {
        if (phase.status === 'running' || phase.status === 'blocked' || phase.status === 'awaiting_clarification') {
            const profile = PHASE_TO_PROFILE[phase.phase];
            if (profile)
                active.add(profile);
        }
    }
    // If task declares roles, those are the active set for context
    if (taskRoles) {
        for (const r of taskRoles.required) {
            if (projectProfiles.includes(r) || ALL_PROFILES.some((p) => p.id === r)) {
                active.add(r);
            }
        }
    }
    return [...active];
}
function resolveInteractions(run) {
    const interactions = [];
    const phases = run.phases;
    for (let i = 0; i < phases.length; i++) {
        const phase = phases[i];
        const nextPhase = phases[i + 1];
        collectPhaseInteractions(phase, nextPhase, interactions);
    }
    return interactions;
}
function collectPhaseInteractions(phase, nextPhase, interactions) {
    if (phase.status === 'done' && nextPhase) {
        interactions.push({
            from: PHASE_TO_PROFILE[phase.phase],
            to: PHASE_TO_PROFILE[nextPhase.phase],
            kind: 'handoff',
            phase: phase.phase,
        });
        return;
    }
    if (phase.status === 'blocked') {
        collectBlockedInteractions(phase, nextPhase, interactions);
        return;
    }
    if (phase.status === 'awaiting_clarification') {
        interactions.push({
            from: PHASE_TO_PROFILE[phase.phase],
            to: 'ta',
            kind: 'clarification',
            phase: phase.phase,
        });
    }
}
function collectBlockedInteractions(phase, nextPhase, interactions) {
    if (phase.notes?.startsWith('Rejected →')) {
        const rejection = parseRejectionTarget(phase.notes);
        if (rejection) {
            interactions.push({ from: PHASE_TO_PROFILE[phase.phase], to: rejection, kind: 'reject', phase: phase.phase });
        }
    }
    if (phase.reviewIds?.length && nextPhase) {
        interactions.push({
            from: PHASE_TO_PROFILE[phase.phase],
            to: PHASE_TO_PROFILE[nextPhase.phase],
            kind: 'gate',
            phase: phase.phase,
        });
    }
}
function parseRejectionTarget(notes) {
    const targetMatch = notes.match(/Rejected → (\w+)/);
    if (!targetMatch)
        return null;
    const targetPhase = targetMatch[1];
    return PHASE_TO_PROFILE[targetPhase] ?? null;
}
//# sourceMappingURL=role-activation.js.map