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;
};
import { Component, ViewChild, inject } from '@angular/core';
import { RegisterClass } from '@memberjunction/global';
import { BaseResourceComponent, NavigationService } from '@memberjunction/ng-shared';
import { buildHistoryAgentContext, resolveRowByIDOrName } from './bulk-operations-agent-helpers';
import * as i0 from "@angular/core";
import * as i1 from "@memberjunction/ng-record-process-studio";
const _c0 = ["history"];
/**
 * "Run History" sub-page of the Bulk Operations shell. A thin host that renders the generic, self-contained
 * `<mj-record-process-history>` (run list + per-record drill-in) scoped to the current provider.
 *
 * Like its Operations sibling, this host wires the surface into the MJ AI-agent stack: it reports the
 * history component's live state via `SetAgentContext` and registers SAFE, READ-ONLY navigation tools via
 * `SetAgentClientTools`. The host reaches the hosted generic component through a {@link ViewChild}
 * reference (`history`) and only reads its public state / calls its public methods.
 *
 * 🚨🚨🚨 SAFETY BOUNDARY — Run History is a read-only audit surface. 🚨🚨🚨
 * Every tool exposed here is read-only / navigational (refresh, view a run's details, go back). There is
 * NOTHING destructive on this surface and there must NEVER be:
 *   - DO NOT add any tool that re-runs, applies, retries, or otherwise mutates a Record Process or its
 *     records. Re-running an operation belongs on the Operations surface and is gated by the runner's
 *     dry-run → user-confirm flow there.
 *   - DO NOT expose any tool that writes to the run / run-detail tables.
 * Viewing history is inert; keep it that way.
 */
let BulkOperationsRunHistoryComponent = class BulkOperationsRunHistoryComponent extends BaseResourceComponent {
    /** Reference to the hosted generic history component — the source of truth for context + tool target. */
    history;
    navigationService = inject(NavigationService);
    async ngOnInit() {
        super.ngOnInit();
        this.NotifyLoadComplete();
    }
    /**
     * Wire agent context + tools once the view (and the `history` ViewChild) is available. The history
     * component finishes its initial `reload()` asynchronously; we publish immediately and rely on each
     * tool Handler to re-publish after acting. A `queueMicrotask` defers the first publish one tick so an
     * already-resolved `ngOnInit` reload is reflected.
     */
    ngAfterViewInit() {
        this.registerAgentTools();
        queueMicrotask(() => this.publishAgentContext());
    }
    ngOnDestroy() {
        super.ngOnDestroy();
    }
    async GetResourceDisplayName(_data) { return 'Run History'; }
    async GetResourceIconClass(_data) { return 'fa-solid fa-clock-rotate-left'; }
    // ================================================================
    // Agent context
    // ================================================================
    /**
     * Publish the history component's live state to the AI agent. Tolerant of the ViewChild not yet being
     * resolved. Re-invoked by every tool Handler after it changes history state, since the generic
     * component emits no change events we could subscribe to.
     */
    publishAgentContext() {
        const h = this.history;
        if (!h) {
            this.navigationService.SetAgentContext(this, { IsViewingRunDetail: false, IsReady: false });
            return;
        }
        const open = h.OpenRunRow;
        this.navigationService.SetAgentContext(this, buildHistoryAgentContext({
            Mode: h.Mode,
            Runs: h.Runs,
            OpenRunID: open?.ID ?? null,
            OpenRunStatus: open?.Status ?? null,
            OpenRunIsDryRun: open?.DryRun ?? null,
            OpenRunProcessName: open?.ProcessName ?? null,
        }));
    }
    // ================================================================
    // Agent client tools (all READ-ONLY / navigational — see SAFETY BOUNDARY)
    // ================================================================
    /**
     * Register the SAFE, read-only agent tools for the Run History surface: refresh the run list, open a
     * run's per-record details, and return to the list. Every Handler is tolerant and re-publishes context.
     */
    registerAgentTools() {
        this.navigationService.SetAgentClientTools(this, [
            {
                Name: 'RefreshRunHistory',
                Description: 'Reload the list of bulk operation runs from the server.',
                ParameterSchema: { type: 'object', properties: {} },
                Handler: async () => this.handleRefresh(),
            },
            {
                Name: 'ViewRunDetails',
                Description: 'Open the per-record detail view for a specific bulk operation run, referenced by its run ID or by the operation name that produced it (a partial, case-insensitive name match resolves to the most recent matching run). Read-only — shows what each record\'s outcome was.',
                ParameterSchema: {
                    type: 'object',
                    properties: { run: { type: 'string', description: 'The ID of the Process Run, or the name of the bulk operation that produced it.' } },
                    required: ['run'],
                },
                Handler: async (params) => this.handleViewDetails(params),
            },
            {
                Name: 'SelectRun',
                Description: 'Open (drill into) a bulk operation run by ID or operation name. Alias of ViewRunDetails for agents that phrase selection as "select" — read-only navigation, opens the per-record detail.',
                ParameterSchema: {
                    type: 'object',
                    properties: { run: { type: 'string', description: 'The ID of the Process Run, or the name of the bulk operation that produced it.' } },
                    required: ['run'],
                },
                Handler: async (params) => this.handleViewDetails(params),
            },
            {
                Name: 'BackToRunList',
                Description: 'Return from a run detail view to the run history list.',
                ParameterSchema: { type: 'object', properties: {} },
                Handler: async () => this.handleBackToList(),
            },
        ]);
    }
    // ================================================================
    // Tool handlers (small, single-purpose, tolerant)
    // ================================================================
    /** Reload the run list, then re-publish context. */
    async handleRefresh() {
        const h = this.requireHistory();
        if (!h)
            return this.notReady();
        await h.reload();
        this.publishAgentContext();
        return { Success: true, Data: { RunCount: h.Runs.length } };
    }
    /** Open a run's per-record details, resolved from the history component's loaded run list by id or operation name. */
    async handleViewDetails(params) {
        const h = this.requireHistory();
        if (!h)
            return this.notReady();
        const run = this.findRun(h, params['run']);
        if (!run.ok)
            return run.result;
        await h.openRun(run.value);
        this.publishAgentContext();
        return { Success: true, Data: { RunID: run.value.ID, ProcessName: run.value.ProcessName, Status: run.value.Status, DryRun: run.value.DryRun } };
    }
    /** Return to the run list from a detail view. */
    async handleBackToList() {
        const h = this.requireHistory();
        if (!h)
            return this.notReady();
        h.backToList();
        this.publishAgentContext();
        return { Success: true };
    }
    // ================================================================
    // Helpers
    // ================================================================
    /** The hosted history component, or undefined if the view isn't ready yet. */
    requireHistory() {
        return this.history;
    }
    /** Typed "not ready" failure for tools invoked before the ViewChild resolves. */
    notReady() {
        return { Success: false, ErrorMessage: 'The run history is still initializing. Please try again in a moment.' };
    }
    /**
     * Resolve a run row from the history component's loaded list by ID OR operation name (delegates to
     * the pure, unit-tested {@link resolveRowByIDOrName} helper: exact run ID → exact operation name →
     * partial operation-name contains). Because runs are listed most-recent-first, a name match yields
     * the most recent run of that operation. Returns a structured failure (listing available operation
     * names) if the param is missing/non-string or no row matches.
     */
    findRun(h, rawRef) {
        return resolveRowByIDOrName(h.Runs, rawRef, 'run', 'bulk operation run', (r) => r.ProcessName);
    }
    static ɵfac = /*@__PURE__*/ (() => { let ɵBulkOperationsRunHistoryComponent_BaseFactory; return function BulkOperationsRunHistoryComponent_Factory(__ngFactoryType__) { return (ɵBulkOperationsRunHistoryComponent_BaseFactory || (ɵBulkOperationsRunHistoryComponent_BaseFactory = i0.ɵɵgetInheritedFactory(BulkOperationsRunHistoryComponent)))(__ngFactoryType__ || BulkOperationsRunHistoryComponent); }; })();
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: BulkOperationsRunHistoryComponent, selectors: [["mj-bulk-operations-run-history"]], viewQuery: function BulkOperationsRunHistoryComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(_c0, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.history = _t.first);
        } }, standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 3, vars: 1, consts: [["history", ""], [1, "bo-host"], [3, "Provider"]], template: function BulkOperationsRunHistoryComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "div", 1);
            i0.ɵɵelement(1, "mj-record-process-history", 2, 0);
            i0.ɵɵelementEnd();
        } if (rf & 2) {
            i0.ɵɵadvance();
            i0.ɵɵproperty("Provider", ctx.ProviderToUse);
        } }, dependencies: [i1.RecordProcessHistoryComponent], styles: [".bo-host[_ngcontent-%COMP%]{padding:20px;height:100%;overflow:auto;box-sizing:border-box}"] });
};
BulkOperationsRunHistoryComponent = __decorate([
    RegisterClass(BaseResourceComponent, 'BulkOperationsRunHistory')
], BulkOperationsRunHistoryComponent);
export { BulkOperationsRunHistoryComponent };
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(BulkOperationsRunHistoryComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-bulk-operations-run-history', template: `<div class="bo-host"><mj-record-process-history #history [Provider]="ProviderToUse"></mj-record-process-history></div>`, styles: [".bo-host{padding:20px;height:100%;overflow:auto;box-sizing:border-box}"] }]
    }], null, { history: [{
            type: ViewChild,
            args: ['history']
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(BulkOperationsRunHistoryComponent, { className: "BulkOperationsRunHistoryComponent", filePath: "src/BulkOperations/bulk-operations-run-history.component.ts", lineNumber: 34 }); })();
//# sourceMappingURL=bulk-operations-run-history.component.js.map