/**
 * UpsertAgentGraphOverrideUseCase
 *
 * Creates a new override or replaces the existing one for the given
 * agentType. Rejects unknown agent types — the user can only override
 * graphs the registry knows about.
 *
 * Validates structural integrity: every edge must reference existing
 * node ids and node ids must be unique. The frontend should pre-validate
 * but the use case re-checks defensively.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { inject, injectable } from 'tsyringe';
import { randomUUID } from 'node:crypto';
import { isKnownGraphAgent, } from '../../services/builtin-graph-registry.js';
let UpsertAgentGraphOverrideUseCase = class UpsertAgentGraphOverrideUseCase {
    overrides;
    customAgents;
    constructor(overrides, customAgents) {
        this.overrides = overrides;
        this.customAgents = customAgents;
    }
    async execute(input) {
        if (!input.agentType.trim())
            throw new Error('agentType is required');
        if (!isKnownGraphAgent(input.agentType)) {
            // Custom agents can carry their own graph descriptors too.
            const custom = await this.customAgents.findByType(input.agentType);
            if (!custom) {
                throw new Error(`Unknown graph agent: ${input.agentType}. ` +
                    'Only agents registered in the built-in graph registry or owned by a custom agent ' +
                    'can have a graph override.');
            }
        }
        if (!Array.isArray(input.nodes) || input.nodes.length === 0) {
            throw new Error('nodes must be a non-empty array');
        }
        if (!Array.isArray(input.edges)) {
            throw new Error('edges must be an array');
        }
        validateStructure(input.nodes, input.edges);
        const existing = await this.overrides.findActive(input.agentType);
        const now = new Date();
        const override = {
            id: existing?.id ?? randomUUID(),
            agentType: input.agentType,
            nodesJson: JSON.stringify(input.nodes),
            edgesJson: JSON.stringify(input.edges),
            version: (existing?.version ?? 0) + 1,
            createdBy: input.createdBy ?? existing?.createdBy ?? 'user',
            createdAt: existing?.createdAt ?? now,
            updatedAt: now,
        };
        if (existing) {
            await this.overrides.update(override);
        }
        else {
            await this.overrides.create(override);
        }
        return override;
    }
};
UpsertAgentGraphOverrideUseCase = __decorate([
    injectable(),
    __param(0, inject('IAgentGraphOverrideRepository')),
    __param(1, inject('ICustomAgentRepository')),
    __metadata("design:paramtypes", [Object, Object])
], UpsertAgentGraphOverrideUseCase);
export { UpsertAgentGraphOverrideUseCase };
function validateStructure(nodes, edges) {
    const ids = new Set();
    for (const node of nodes) {
        if (!node.id?.trim())
            throw new Error('every node must have a non-empty id');
        if (!node.label?.trim())
            throw new Error(`node ${node.id} must have a non-empty label`);
        if (ids.has(node.id))
            throw new Error(`duplicate node id: ${node.id}`);
        ids.add(node.id);
    }
    for (const edge of edges) {
        if (!ids.has(edge.from))
            throw new Error(`edge references unknown source node: ${edge.from}`);
        if (!ids.has(edge.to))
            throw new Error(`edge references unknown target node: ${edge.to}`);
    }
}
