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;
};
/**
 * @fileoverview Archive Runs Resource Component
 *
 * Dashboard resource wrapper for the "Run History" tab in the Archiving application.
 * Delegates all rendering to the reusable mj-archive-run-viewer component from
 * @memberjunction/ng-archive-manager.
 *
 * Beyond rendering, this wrapper reports a READ-ONLY summary of the archive run
 * history to the AI agent (outcome counts, active status filter, which run's
 * detail drawer is open) and exposes read-only filter/refresh/view tools. The
 * inner run viewer publishes its loaded runs (`Runs`) and an `OpenRunDrawer`
 * method that this wrapper drives for the view-detail tool.
 *
 * 🔒 SAFETY BOUNDARY (READ-ONLY / VIEW-ONLY): this surface NEVER exposes run
 * execution or mutation to the agent. The following are intentionally NOT wired
 * as client tools: RunArchiveNow / execute, CancelRunningArchive,
 * RetryFailedArchiveRun, PurgeArchivedData, and ModifyArchivePolicy. The agent
 * may only filter, refresh, and open a run's detail drawer (by ID or
 * configuration/policy name) for inspection. SelectRun / ViewArchiveRunDetail
 * open the drawer for VIEWING only — they perform no execution or mutation.
 */
import { Component, ViewChild } from '@angular/core';
import { RegisterClass, UUIDsEqual } from '@memberjunction/global';
import { BaseResourceComponent } from '@memberjunction/ng-shared';
import { ArchiveRunViewerComponent } from '@memberjunction/ng-archive-manager';
import { buildArchiveRunsAgentContext, computeArchiveRunStatusCounts, filterArchiveRunsByStatus, isValidArchiveRunStatusFilter, resolveArchiveRun, ARCHIVE_RUN_STATUS_FILTERS, ARCHIVE_NAME_LIST_CAP, } from '../archive-agent-context';
import * as i0 from "@angular/core";
import * as i1 from "@memberjunction/ng-archive-manager";
import * as i2 from "@memberjunction/ng-ui-components";
let ArchiveRunsResourceComponent = class ArchiveRunsResourceComponent extends BaseResourceComponent {
    /** Reference to the inner run viewer — source of loaded runs + the detail drawer. */
    runViewer;
    /** Wrapper-owned status filter (defaults to no filter). */
    statusFilter = 'all';
    ngAfterViewInit() {
        this.publishAgentContext();
        this.registerAgentClientTools();
        this.NotifyLoadComplete();
    }
    ngOnDestroy() {
        super.ngOnDestroy();
    }
    async GetResourceDisplayName(_data) {
        return 'Archive Run History';
    }
    async GetResourceIconClass(_data) {
        return 'fa-solid fa-clock-rotate-left';
    }
    // ========================================
    // AI AGENT CONTEXT & CLIENT TOOLS (READ-ONLY / VIEW-ONLY)
    // ========================================
    /**
     * Publish the current run-history summary to the AI agent. Read-only —
     * describes outcome counts, the active filter, and which run (if any) is open.
     */
    publishAgentContext() {
        const runs = this.loadedRuns();
        const counts = computeArchiveRunStatusCounts(runs);
        const filtered = filterArchiveRunsByStatus(runs, this.statusFilter);
        const selected = this.runViewer?.SelectedRun ?? null;
        const recentRuns = filtered
            .slice(0, ARCHIVE_NAME_LIST_CAP)
            .map((r) => ({ ID: r.ID, Name: r.ConfigurationName, Status: r.Status }));
        const input = {
            Counts: counts,
            StatusFilter: this.statusFilter,
            FilteredRunCount: filtered.length,
            SelectedRunId: selected?.ID ?? null,
            SelectedRunName: selected?.ConfigurationName ?? null,
            SelectedRunStatus: selected?.Status ?? null,
            RecentRuns: recentRuns,
            IsLoading: this.runViewer?.IsLoading ?? false,
        };
        this.navigationService.SetAgentContext(this, buildArchiveRunsAgentContext(input));
    }
    /**
     * The runs currently loaded in the inner viewer, narrowed to the
     * {@link ArchiveRunSnapshot} shape the pure helpers consume. The viewer's
     * `ArchiveRunSummary` is structurally compatible (ID · ConfigurationName ·
     * Status); this keeps the cast in one place.
     */
    loadedRuns() {
        return (this.runViewer?.Runs ?? []);
    }
    /**
     * Register the read-only client tools for this surface.
     *
     * 🔒 Filter / refresh / view-detail only. No run execution, cancellation,
     * retry, or purge is exposed (see SAFETY BOUNDARY).
     */
    registerAgentClientTools() {
        this.navigationService.SetAgentClientTools(this, [
            {
                Name: 'FilterArchiveRunsByStatus',
                Description: `Filter the archive run history by status. Valid values: ${ARCHIVE_RUN_STATUS_FILTERS.join(', ')} ('all' clears the filter). Read-only — changes only the agent-visible filtered count.`,
                ParameterSchema: {
                    type: 'object',
                    properties: { status: { type: 'string', enum: [...ARCHIVE_RUN_STATUS_FILTERS] } },
                    required: ['status'],
                },
                Handler: async (params) => this.toolFilterByStatus(params),
            },
            {
                Name: 'RefreshArchiveRunHistory',
                Description: 'Reload the archive run history. Read-only — re-reads runs and re-publishes the summary.',
                ParameterSchema: { type: 'object', properties: {} },
                Handler: async () => this.toolRefreshRunHistory(),
            },
            {
                Name: 'ViewArchiveRunDetail',
                Description: 'Open the detail drawer for a specific archive run — by its ID or by its configuration/policy name — to inspect its archived records. Resolution: exact ID, then exact name, then a name-contains match. View-only — performs no execution or mutation.',
                ParameterSchema: {
                    type: 'object',
                    properties: { run: { type: 'string', description: 'Run ID or configuration/policy name.' } },
                    required: ['run'],
                },
                Handler: async (params) => this.toolViewRunDetail(params),
            },
            {
                Name: 'SelectRun',
                Description: 'Alias of ViewArchiveRunDetail: open a run by ID or configuration/policy name for inspection. View-only.',
                ParameterSchema: {
                    type: 'object',
                    properties: { run: { type: 'string', description: 'Run ID or configuration/policy name.' } },
                    required: ['run'],
                },
                Handler: async (params) => this.toolViewRunDetail(params),
            },
        ]);
    }
    /** Apply a status filter (wrapper-owned) and re-publish context. Never throws. */
    toolFilterByStatus(params) {
        const raw = params['status'];
        if (!isValidArchiveRunStatusFilter(raw)) {
            return {
                Success: false,
                ErrorMessage: `Invalid status "${String(raw)}". Expected one of: ${ARCHIVE_RUN_STATUS_FILTERS.join(', ')}.`,
            };
        }
        this.statusFilter = raw;
        const filteredCount = filterArchiveRunsByStatus(this.loadedRuns(), this.statusFilter).length;
        this.publishAgentContext();
        return { Success: true, Data: { StatusFilter: this.statusFilter, FilteredRunCount: filteredCount } };
    }
    /**
     * Refresh the run history. The inner viewer loads its data in ngOnInit and
     * exposes no public reload, so the wrapper re-publishes the latest context
     * from the inner viewer's current state. Never throws.
     */
    toolRefreshRunHistory() {
        if (!this.runViewer) {
            return { Success: false, ErrorMessage: 'The run history view is not ready yet.' };
        }
        this.publishAgentContext();
        return { Success: true };
    }
    /**
     * Open the detail drawer for a run by ID or configuration/policy name
     * (view-only). Accepts the agent's `run` parameter and resolves it via the
     * pure {@link resolveArchiveRun} helper (exact ID → exact name → name-contains).
     * Never throws.
     */
    async toolViewRunDetail(params) {
        const reference = typeof params['run'] === 'string' ? params['run'] : '';
        if (!reference) {
            return { Success: false, ErrorMessage: 'A run ID or configuration/policy name is required.' };
        }
        if (!this.runViewer) {
            return { Success: false, ErrorMessage: 'The run history view is not ready yet.' };
        }
        const resolution = resolveArchiveRun(reference, this.loadedRuns());
        if (!resolution.ok) {
            return { Success: false, ErrorMessage: resolution.error };
        }
        // OpenRunDrawer wants the viewer's own run object; the resolved snapshot
        // shares the same ID, so re-find by ID to hand back the live reference.
        const run = this.runViewer.Runs.find((r) => UUIDsEqual(r.ID, resolution.run.ID));
        if (!run) {
            return { Success: false, ErrorMessage: `No archive run found with ID "${resolution.run.ID}".` };
        }
        await this.runViewer.OpenRunDrawer(run);
        this.publishAgentContext();
        return { Success: true, Data: { SelectedRunId: run.ID, SelectedRunName: run.ConfigurationName, SelectedRunStatus: run.Status } };
    }
    static ɵfac = /*@__PURE__*/ (() => { let ɵArchiveRunsResourceComponent_BaseFactory; return function ArchiveRunsResourceComponent_Factory(__ngFactoryType__) { return (ɵArchiveRunsResourceComponent_BaseFactory || (ɵArchiveRunsResourceComponent_BaseFactory = i0.ɵɵgetInheritedFactory(ArchiveRunsResourceComponent)))(__ngFactoryType__ || ArchiveRunsResourceComponent); }; })();
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: ArchiveRunsResourceComponent, selectors: [["app-archive-runs-resource"]], viewQuery: function ArchiveRunsResourceComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(ArchiveRunViewerComponent, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.runViewer = _t.first);
        } }, standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 4, vars: 2, consts: [["Title", "Archive Run History", "Icon", "fa-solid fa-clock-rotate-left", "Subtitle", "Execution history and results for archive jobs"], [3, "Flex", "Padding"]], template: function ArchiveRunsResourceComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "mj-page-layout");
            i0.ɵɵelement(1, "mj-page-header", 0);
            i0.ɵɵelementStart(2, "mj-page-body", 1);
            i0.ɵɵelement(3, "mj-archive-run-viewer");
            i0.ɵɵelementEnd()();
        } if (rf & 2) {
            i0.ɵɵadvance(2);
            i0.ɵɵproperty("Flex", true)("Padding", false);
        } }, dependencies: [i1.ArchiveRunViewerComponent, i2.MJPageLayoutComponent, i2.MJPageHeaderComponent, i2.MJPageBodyComponent], styles: ["[_nghost-%COMP%] { display: block; height: 100%; width: 100%; }"] });
};
ArchiveRunsResourceComponent = __decorate([
    RegisterClass(BaseResourceComponent, 'ArchiveRunsResource')
], ArchiveRunsResourceComponent);
export { ArchiveRunsResourceComponent };
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ArchiveRunsResourceComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'app-archive-runs-resource', template: `
        <mj-page-layout>
            <mj-page-header
                Title="Archive Run History"
                Icon="fa-solid fa-clock-rotate-left"
                Subtitle="Execution history and results for archive jobs">
            </mj-page-header>
            <mj-page-body [Flex]="true" [Padding]="false">
                <mj-archive-run-viewer></mj-archive-run-viewer>
            </mj-page-body>
        </mj-page-layout>
    `, styles: [":host { display: block; height: 100%; width: 100%; }"] }]
    }], null, { runViewer: [{
            type: ViewChild,
            args: [ArchiveRunViewerComponent]
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(ArchiveRunsResourceComponent, { className: "ArchiveRunsResourceComponent", filePath: "src/Archiving/components/archive-runs-resource.component.ts", lineNumber: 61 }); })();
export function LoadArchiveRunsResource() {
    // Prevents tree-shaking
}
//# sourceMappingURL=archive-runs-resource.component.js.map