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 { UserRoutineEngine } from '@memberjunction/core-entities';
import { CompositeKey } from '@memberjunction/core';
import { validateStringParam } from '../shared/agent-tool-validation';
import { buildUserRoutinesAgentContext, resolveRoutineByIDOrName } from './user-routines-agent-context';
import * as i0 from "@angular/core";
import * as i1 from "@memberjunction/ng-ui-components";
import * as i2 from "@memberjunction/ng-user-routines";
const _c0 = ["commandCenter"];
function UserRoutinesResourceComponent_Conditional_5_Template(rf, ctx) { if (rf & 1) {
    const _r2 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "button", 14);
    i0.ɵɵlistener("click", function UserRoutinesResourceComponent_Conditional_5_Template_button_click_0_listener() { i0.ɵɵrestoreView(_r2); const ctx_r2 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r2.BackToList()); });
    i0.ɵɵelement(1, "i", 15);
    i0.ɵɵtext(2, " Back to list ");
    i0.ɵɵelementEnd();
} }
/**
 * Routines app — full-page Explorer host for the User Routines command center
 * (list / create-edit / run history). Thin chrome-trio wrapper over the generic
 * `<mj-user-routines-command-center>` from `@memberjunction/ng-user-routines`.
 *
 * Query-param round trip: `routine=<id>` opens that routine's history view; the pair
 * `initial read` + `OnQueryParamsChanged` keeps deep links, Home pins, and
 * back/forward working on cached instances.
 *
 * 🚨 SAFETY BOUNDARY 🚨 (see user-routines-agent-context.ts for the full statement)
 * Agent tools here are navigation / filter / search / select / refresh ONLY. The
 * agent may OPEN the editor (CreateRoutine / OpenRoutineEditor) but can never save,
 * delete, pause/resume, or run-now a routine — those stay human-driven in the UI.
 */
let UserRoutinesResourceComponent = class UserRoutinesResourceComponent extends BaseResourceComponent {
    navigationService = inject(NavigationService);
    commandCenter;
    SearchText = '';
    StatusFilter = 'all';
    TotalCount = 0;
    FilteredCount = 0;
    ActiveView = 'list';
    SelectedRoutineID = null;
    FilterFields = [
        {
            key: 'status',
            type: 'dropdown',
            label: 'Status',
            icon: 'fa-solid fa-circle-half-stroke',
            options: [
                { text: 'All statuses', value: 'all' },
                { text: 'Active', value: 'Active' },
                { text: 'Paused', value: 'Paused' },
                { text: 'Disabled', value: 'Disabled' },
            ],
        },
    ];
    FilterValues = { status: 'all' };
    get ActiveFilterCount() {
        return this.StatusFilter === 'all' ? 0 : 1;
    }
    async ngOnInit() {
        super.ngOnInit();
        // 1) Initial query-param read (deep links)
        const params = this.GetQueryParams();
        if (params['routine']) {
            this.SelectedRoutineID = params['routine'];
        }
        this.registerAgentTools();
        this.publishAgentContext();
        this.NotifyLoadComplete();
    }
    async GetResourceDisplayName(_data) {
        return 'Routines';
    }
    async GetResourceIconClass(_data) {
        return 'fa-solid fa-business-time';
    }
    /** 2) React to later query-param changes (back/forward, pins, cached re-focus). */
    OnQueryParamsChanged(params, _source) {
        const routineId = params['routine'] || null;
        if (routineId !== this.SelectedRoutineID) {
            this.SelectedRoutineID = routineId;
        }
    }
    // ---------------------------------------------------------------
    // Command-center wiring
    // ---------------------------------------------------------------
    OnSelectedRoutineIDChange(routineId) {
        this.SelectedRoutineID = routineId;
        this.UpdateQueryParams({ routine: routineId });
        this.publishAgentContext();
    }
    OnViewChanged(view) {
        this.ActiveView = view;
        this.publishAgentContext();
    }
    OnCountsChanged(counts) {
        this.TotalCount = counts.Total;
        this.FilteredCount = counts.Filtered;
        this.publishAgentContext();
    }
    /** Opens the linked execution record (Agent Run / Prompt Run / Action Log) in a tab. */
    OnHistoryRecordOpened(args) {
        this.navigationService.OpenEntityRecord(args.EntityName, CompositeKey.FromID(args.RecordID));
    }
    OnSearchChange(value) {
        this.SearchText = value;
        this.publishAgentContext();
    }
    OnFilterValuesChange(values) {
        this.FilterValues = values;
        const status = values['status'];
        this.StatusFilter = (status === 'Active' || status === 'Paused' || status === 'Disabled') ? status : 'all';
        this.publishAgentContext();
    }
    ResetFilters() {
        this.OnFilterValuesChange({ status: 'all' });
    }
    NewRoutine() {
        this.commandCenter?.ShowNewRoutine();
    }
    BackToList() {
        this.commandCenter?.ShowList();
    }
    async RefreshData() {
        await this.commandCenter?.Refresh();
        this.publishAgentContext();
    }
    // ---------------------------------------------------------------
    // Agent context + tools (navigation/read-only — see SAFETY BOUNDARY)
    // ---------------------------------------------------------------
    publishAgentContext() {
        this.navigationService.SetAgentContext(this, buildUserRoutinesAgentContext({
            ActiveView: this.ActiveView,
            SearchText: this.SearchText,
            StatusFilter: this.StatusFilter,
            TotalCount: this.TotalCount,
            FilteredCount: this.FilteredCount,
            SelectedRoutineID: this.SelectedRoutineID,
            Routines: this.routineRows(),
        }));
    }
    routineRows() {
        const engine = UserRoutineEngine.GetProviderInstance(this.ProviderToUse, UserRoutineEngine);
        return engine.Routines.map((r) => ({ ID: r.ID, Name: r.Name, Status: r.Status }));
    }
    registerAgentTools() {
        this.navigationService.SetAgentClientTools(this, [
            {
                Name: 'RefreshRoutines',
                Description: 'Reload the routines list from the server.',
                ParameterSchema: { type: 'object', properties: {} },
                Handler: async () => {
                    await this.RefreshData();
                    return { Success: true, Data: { TotalRoutineCount: this.TotalCount } };
                },
            },
            {
                Name: 'SearchRoutines',
                Description: 'Filter the routines list by a search query (name, description, or agent). Pass an empty string to clear.',
                ParameterSchema: {
                    type: 'object',
                    properties: { query: { type: 'string', description: 'Text to filter by; empty clears.' } },
                    required: ['query'],
                },
                Handler: async (params) => this.handleSearch(params),
            },
            {
                Name: 'FilterRoutinesByStatus',
                Description: "Filter routines by lifecycle status: 'Active', 'Paused', 'Disabled', or 'all'.",
                ParameterSchema: {
                    type: 'object',
                    properties: { status: { type: 'string', description: "'Active' | 'Paused' | 'Disabled' | 'all'" } },
                    required: ['status'],
                },
                Handler: async (params) => this.handleStatusFilter(params),
            },
            {
                Name: 'SelectRoutine',
                Description: "Open a routine's run history, referenced by ID or name (partial, case-insensitive match accepted).",
                ParameterSchema: {
                    type: 'object',
                    properties: { routine: { type: 'string', description: 'The routine ID or name.' } },
                    required: ['routine'],
                },
                Handler: async (params) => this.handleSelect(params),
            },
            {
                Name: 'OpenRoutineEditor',
                Description: 'Open the editor for an existing routine (by ID or name). This only opens the editor for the user — it does NOT save anything.',
                ParameterSchema: {
                    type: 'object',
                    properties: { routine: { type: 'string', description: 'The routine ID or name.' } },
                    required: ['routine'],
                },
                Handler: async (params) => this.handleEdit(params),
            },
            {
                Name: 'CreateRoutine',
                Description: 'Open the New Routine editor. This only opens the editor for the user — it does NOT save anything.',
                ParameterSchema: { type: 'object', properties: {} },
                Handler: async () => {
                    this.NewRoutine();
                    this.publishAgentContext();
                    return { Success: true };
                },
            },
            {
                Name: 'BackToRoutinesList',
                Description: 'Return from the editor or history view to the routines list.',
                ParameterSchema: { type: 'object', properties: {} },
                Handler: async () => {
                    this.BackToList();
                    this.publishAgentContext();
                    return { Success: true };
                },
            },
        ]);
    }
    async handleSearch(params) {
        const check = validateStringParam(params['query'], 'query');
        if (!check.ok) {
            return check.result;
        }
        this.OnSearchChange(check.value);
        return { Success: true, Data: { FilteredRoutineCount: this.FilteredCount } };
    }
    async handleStatusFilter(params) {
        const check = validateStringParam(params['status'], 'status');
        if (!check.ok) {
            return check.result;
        }
        const value = check.value.trim();
        const normalized = ['Active', 'Paused', 'Disabled'].find((s) => s.toLowerCase() === value.toLowerCase());
        if (!normalized && value.toLowerCase() !== 'all') {
            return { Success: false, ErrorMessage: `'${value}' is not a valid status. Use 'Active', 'Paused', 'Disabled', or 'all'.` };
        }
        this.OnFilterValuesChange({ status: normalized ?? 'all' });
        return { Success: true };
    }
    async handleSelect(params) {
        const resolved = resolveRoutineByIDOrName(this.routineRows(), params['routine']);
        if (!resolved.ok) {
            return { Success: false, ErrorMessage: resolved.error };
        }
        this.commandCenter?.ShowHistory(resolved.value.ID);
        this.publishAgentContext();
        return { Success: true, Data: { RoutineID: resolved.value.ID, RoutineName: resolved.value.Name } };
    }
    async handleEdit(params) {
        const resolved = resolveRoutineByIDOrName(this.routineRows(), params['routine']);
        if (!resolved.ok) {
            return { Success: false, ErrorMessage: resolved.error };
        }
        this.commandCenter?.ShowEditRoutine(resolved.value.ID);
        this.publishAgentContext();
        return { Success: true, Data: { RoutineID: resolved.value.ID, RoutineName: resolved.value.Name } };
    }
    static ɵfac = /*@__PURE__*/ (() => { let ɵUserRoutinesResourceComponent_BaseFactory; return function UserRoutinesResourceComponent_Factory(__ngFactoryType__) { return (ɵUserRoutinesResourceComponent_BaseFactory || (ɵUserRoutinesResourceComponent_BaseFactory = i0.ɵɵgetInheritedFactory(UserRoutinesResourceComponent)))(__ngFactoryType__ || UserRoutinesResourceComponent); }; })();
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: UserRoutinesResourceComponent, selectors: [["mj-user-routines-resource"]], viewQuery: function UserRoutinesResourceComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(_c0, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.commandCenter = _t.first);
        } }, standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 17, vars: 13, consts: [["commandCenter", ""], ["Title", "Routines", "Icon", "fa-solid fa-business-time", "Subtitle", "Schedule AI agents to run for you \u2014 and get notified about the results"], ["meta", ""], ["Label", "routines", 3, "Count", "Total"], ["actions", ""], ["mjButton", "", "variant", "outline", "size", "sm"], [3, "Clicked"], ["mjButton", "", "variant", "primary", "size", "sm", 3, "click"], [1, "fa-solid", "fa-plus"], ["toolbar", ""], ["Placeholder", "Search routines...", 3, "ValueChange", "Value"], ["Label", "Filters", "Icon", "fa-solid fa-filter", 3, "ClearAllRequested", "ActiveCount", "ShowClearAll"], [3, "ValuesChange", "Reset", "Fields", "Values"], [1, "routines-cc", 3, "SelectedRoutineIDChange", "ViewChanged", "CountsChanged", "HistoryRecordOpened", "Provider", "ShowHeader", "SearchText", "StatusFilter", "SelectedRoutineID"], ["mjButton", "", "variant", "outline", "size", "sm", 3, "click"], [1, "fa-solid", "fa-arrow-left"]], template: function UserRoutinesResourceComponent_Template(rf, ctx) { if (rf & 1) {
            const _r1 = i0.ɵɵgetCurrentView();
            i0.ɵɵelementStart(0, "mj-page-layout")(1, "mj-page-header", 1)(2, "div", 2);
            i0.ɵɵelement(3, "mj-stat-badge", 3);
            i0.ɵɵelementEnd();
            i0.ɵɵelementStart(4, "div", 4);
            i0.ɵɵconditionalCreate(5, UserRoutinesResourceComponent_Conditional_5_Template, 3, 0, "button", 5);
            i0.ɵɵelementStart(6, "mj-refresh-button", 6);
            i0.ɵɵlistener("Clicked", function UserRoutinesResourceComponent_Template_mj_refresh_button_Clicked_6_listener() { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.RefreshData()); });
            i0.ɵɵelementEnd();
            i0.ɵɵelementStart(7, "button", 7);
            i0.ɵɵlistener("click", function UserRoutinesResourceComponent_Template_button_click_7_listener() { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.NewRoutine()); });
            i0.ɵɵelement(8, "i", 8);
            i0.ɵɵtext(9, " New Routine ");
            i0.ɵɵelementEnd()();
            i0.ɵɵelementStart(10, "div", 9)(11, "mj-page-search", 10);
            i0.ɵɵlistener("ValueChange", function UserRoutinesResourceComponent_Template_mj_page_search_ValueChange_11_listener($event) { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.OnSearchChange($event)); });
            i0.ɵɵelementEnd();
            i0.ɵɵelementStart(12, "mj-filter-popover", 11);
            i0.ɵɵlistener("ClearAllRequested", function UserRoutinesResourceComponent_Template_mj_filter_popover_ClearAllRequested_12_listener() { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.ResetFilters()); });
            i0.ɵɵelementStart(13, "mj-filter-panel", 12);
            i0.ɵɵlistener("ValuesChange", function UserRoutinesResourceComponent_Template_mj_filter_panel_ValuesChange_13_listener($event) { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.OnFilterValuesChange($event)); })("Reset", function UserRoutinesResourceComponent_Template_mj_filter_panel_Reset_13_listener() { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.ResetFilters()); });
            i0.ɵɵelementEnd()()()();
            i0.ɵɵelementStart(14, "mj-page-body")(15, "mj-user-routines-command-center", 13, 0);
            i0.ɵɵlistener("SelectedRoutineIDChange", function UserRoutinesResourceComponent_Template_mj_user_routines_command_center_SelectedRoutineIDChange_15_listener($event) { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.OnSelectedRoutineIDChange($event)); })("ViewChanged", function UserRoutinesResourceComponent_Template_mj_user_routines_command_center_ViewChanged_15_listener($event) { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.OnViewChanged($event)); })("CountsChanged", function UserRoutinesResourceComponent_Template_mj_user_routines_command_center_CountsChanged_15_listener($event) { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.OnCountsChanged($event)); })("HistoryRecordOpened", function UserRoutinesResourceComponent_Template_mj_user_routines_command_center_HistoryRecordOpened_15_listener($event) { i0.ɵɵrestoreView(_r1); return i0.ɵɵresetView(ctx.OnHistoryRecordOpened($event)); });
            i0.ɵɵelementEnd()()();
        } if (rf & 2) {
            i0.ɵɵadvance(3);
            i0.ɵɵproperty("Count", ctx.FilteredCount)("Total", ctx.TotalCount);
            i0.ɵɵadvance(2);
            i0.ɵɵconditional(ctx.ActiveView !== "list" ? 5 : -1);
            i0.ɵɵadvance(6);
            i0.ɵɵproperty("Value", ctx.SearchText);
            i0.ɵɵadvance();
            i0.ɵɵproperty("ActiveCount", ctx.ActiveFilterCount)("ShowClearAll", ctx.ActiveFilterCount > 0);
            i0.ɵɵadvance();
            i0.ɵɵproperty("Fields", ctx.FilterFields)("Values", ctx.FilterValues);
            i0.ɵɵadvance(2);
            i0.ɵɵproperty("Provider", ctx.ProviderToUse)("ShowHeader", false)("SearchText", ctx.SearchText)("StatusFilter", ctx.StatusFilter)("SelectedRoutineID", ctx.SelectedRoutineID);
        } }, dependencies: [i1.MJButtonDirective, i1.MJPageLayoutComponent, i1.MJPageHeaderComponent, i1.MJPageBodyComponent, i1.MJPageSearchComponent, i1.MJFilterPopoverComponent, i1.MJFilterPanelComponent, i1.MJRefreshButtonComponent, i1.MJStatBadgeComponent, i2.UserRoutinesCommandCenterComponent], styles: ["[_nghost-%COMP%] {\n    display: block;\n    height: 100%;\n}\n\n.routines-cc[_ngcontent-%COMP%] {\n    display: block;\n    height: 100%;\n    min-height: 0;\n}"] });
};
UserRoutinesResourceComponent = __decorate([
    RegisterClass(BaseResourceComponent, 'UserRoutines')
], UserRoutinesResourceComponent);
export { UserRoutinesResourceComponent };
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(UserRoutinesResourceComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-user-routines-resource', template: "<mj-page-layout>\n  <mj-page-header Title=\"Routines\" Icon=\"fa-solid fa-business-time\"\n    Subtitle=\"Schedule AI agents to run for you \u2014 and get notified about the results\">\n    <!-- X-of-Y filtered count earns its meta spot per chrome conventions \u00A72. -->\n    <div meta>\n      <mj-stat-badge [Count]=\"FilteredCount\" [Total]=\"TotalCount\" Label=\"routines\"></mj-stat-badge>\n    </div>\n    <div actions>\n      @if (ActiveView !== 'list') {\n        <button mjButton variant=\"outline\" size=\"sm\" (click)=\"BackToList()\">\n          <i class=\"fa-solid fa-arrow-left\"></i> Back to list\n        </button>\n      }\n      <mj-refresh-button (Clicked)=\"RefreshData()\"></mj-refresh-button>\n      <button mjButton variant=\"primary\" size=\"sm\" (click)=\"NewRoutine()\">\n        <i class=\"fa-solid fa-plus\"></i> New Routine\n      </button>\n    </div>\n    <div toolbar>\n      <mj-page-search Placeholder=\"Search routines...\" [Value]=\"SearchText\"\n        (ValueChange)=\"OnSearchChange($event)\"></mj-page-search>\n      <mj-filter-popover Label=\"Filters\" Icon=\"fa-solid fa-filter\"\n        [ActiveCount]=\"ActiveFilterCount\" [ShowClearAll]=\"ActiveFilterCount > 0\"\n        (ClearAllRequested)=\"ResetFilters()\">\n        <mj-filter-panel [Fields]=\"FilterFields\" [Values]=\"FilterValues\"\n          (ValuesChange)=\"OnFilterValuesChange($event)\" (Reset)=\"ResetFilters()\"></mj-filter-panel>\n      </mj-filter-popover>\n    </div>\n  </mj-page-header>\n\n  <mj-page-body>\n    <mj-user-routines-command-center #commandCenter class=\"routines-cc\"\n      [Provider]=\"ProviderToUse\"\n      [ShowHeader]=\"false\"\n      [SearchText]=\"SearchText\"\n      [StatusFilter]=\"StatusFilter\"\n      [SelectedRoutineID]=\"SelectedRoutineID\"\n      (SelectedRoutineIDChange)=\"OnSelectedRoutineIDChange($event)\"\n      (ViewChanged)=\"OnViewChanged($event)\"\n      (CountsChanged)=\"OnCountsChanged($event)\"\n      (HistoryRecordOpened)=\"OnHistoryRecordOpened($event)\">\n    </mj-user-routines-command-center>\n  </mj-page-body>\n</mj-page-layout>\n", styles: [":host {\n    display: block;\n    height: 100%;\n}\n\n.routines-cc {\n    display: block;\n    height: 100%;\n    min-height: 0;\n}\n"] }]
    }], null, { commandCenter: [{
            type: ViewChild,
            args: ['commandCenter']
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(UserRoutinesResourceComponent, { className: "UserRoutinesResourceComponent", filePath: "src/UserRoutines/user-routines-resource.component.ts", lineNumber: 38 }); })();
/** Tree-shaking prevention — referenced from the package public API. */
export function LoadUserRoutinesResource() {
    // Intentionally empty: forces inclusion of the @RegisterClass side effect.
}
//# sourceMappingURL=user-routines-resource.component.js.map