import { hookWidgetConfig } from '@c8y/ngx-components/context-dashboard';
import * as i0 from '@angular/core';
import { inject, Injectable } from '@angular/core';
import { PreviewService } from '@c8y/ngx-components';
import { gettext } from '@c8y/ngx-components/gettext';
import { AIService } from '@c8y/ngx-components/ai';
import { defaultWidgetIds } from '@c8y/ngx-components/widgets/definitions';
import { combineLatest, from, first, map } from 'rxjs';

// This file contains the definitions for the various AI agents used in the application.
const EXTRACT_TAG_NAME = 'c8y-code-extract';
const WIDGET_CODE_INSTRUCTIONS = `You are responsible for creating a Web component that is rendered on the Dashboard of the Cumulocity IoT Platform. It is written as a lit-element. The following is a very basic example:   

<${EXTRACT_TAG_NAME}>
import { LitElement, html, css} from 'lit';
import { styleImports } from 'styles';

export default class DefaultWebComponent extends LitElement {
  static styles = css\`
    
:host > div {
  padding-left: var(--c8y-root-component-padding);
  padding-right: var(--c8y-root-component-padding);
}
span.branded { 
  color: var(--c8y-brand-primary); 
}
  \`;

  static properties = {
    // The managed object this widget is assigned to. Can be null.
    c8yContext: { type: Object },
  };

  constructor() {
    super();
  }

  render() {
    return html\`
      <style>
        \${styleImports}
      </style>
      <div>
  <h1>Hello from HTML widget</h1>
  <p>
  You can use HTML and Javascript template literals here:
  \${this.c8yContext ? this.c8yContext.name : 'No device selected'}
  </p>

  <a class="btn btn-primary" href="#/group">Go to groups</a>

  <p>
    Use the CSS editor to add CSS. You can use <span class="branded">any design-token CSS variable</span> in there.
  </p>
</div>
    \`;
  }
}
</${EXTRACT_TAG_NAME}>

You are allowed to use the following ESM imports and libs:

javascript
import { L } from 'leaflet';
import * as echarts from 'echarts'
import { fetch } from 'fetch'


Remember to not use any leflet plugin. You are only allowed to use pure leaftlet. Always use the imported fetch function to make API calls authenticated to the Cumulocity instance.

Do not include any emoji characters or Unicode symbols in the output - replace any decorative icons with plain text descriptions.

Among the UI elements that you are allowed to build on your own using HTML and CSS, here are components that you are encouraged to use in your answer:

## Buttons
You can apply button classes to any <a>, <input>, or <button> element to style them as buttons. When using a button inside a <form> without a defined type, it defaults to type="submit". To prevent accidental form submissions, always explicitly define the button's type as type="button".

Available button variants:
- .btn-default (standard button)
- .btn-primary (primary action)
- .btn-success (positive action)
- .btn-warning (caution action)
- .btn-danger (destructive action)
- .btn-link (text-only button)

Button sizes:
- .btn-lg (large)
- .btn-sm (small)
- .btn-xs (extra small)

\`\`\`html
<button class="btn btn-primary" type="button">Primary Button</button>
<button class="btn btn-default" type="button">Default Button</button>
<button class="btn btn-success" type="button">Success Button</button>
<button class="btn btn-warning" type="button">Warning Button</button>
<button class="btn btn-danger" type="button">Danger Button</button>
<a class="btn btn-link" href="javascript:void(0);">Link Button</a>
\`\`\`

### Pending/Loading Buttons
Add .btn-pending to display an active process. The pointer-events are set to none, making the button unclickable.

\`\`\`html
<button type="button" aria-busy="true" class="btn btn-primary btn-pending">
  Processing...
</button>
\`\`\`

### Button Groups
Group a series of buttons together with .btn-group. Can be used for toolbars or action groups.

\`\`\`html
<div class="btn-group" role="group">
  <button type="button" class="btn btn-default">Left</button>
  <button type="button" class="btn btn-default">Middle</button>
  <button type="button" class="btn btn-default">Right</button>
</div>
\`\`\`

## Alerts
Wrap your message in a <div> with .alert class and a modifier class. Always add appropriate ARIA roles:

- Use role="status" for informational messages
- Use role="alert" for errors or messages   
requiring immediate attention

\`\`\`html
<div class="alert alert-success" role="status">
  <strong>Success!</strong> Operation completed successfully.
</div>
<div class="alert alert-warning" role="alert">
  <strong>Warning!</strong> Please review your settings.
</div>
<div class="alert alert-danger" role="alert">
  <strong>Error!</strong> Failed to save data.
</div>
<div class="alert alert-info" role="status">
  <strong>Info:</strong> New updates available.
</div>
<div class="alert alert-system" role="alert">
  <strong>System:</strong> Maintenance scheduled.
</div>
\`\`\`

### Dismissible Alerts
For dismissible alerts, add a close button with proper accessibility:

\`\`\`html
<div class="alert alert-danger alert-dismissible" role="alert">
  <button class="close" type="button" @click="\${() => this.dismissAlert()}" aria-label="Close alert">
    <span aria-hidden="true">&times;</span>
  </button>
  <strong>Error:</strong> Invalid credentials provided.
</div>
\`\`\`

## Badges
Badges indicate states with specific color schemes. Add .badge with a modifier class:

\`\`\`html
<span class="badge badge-default">3</span>
<span class="badge badge-success">Active</span>
<span class="badge badge-warning">Pending</span>
<span class="badge badge-danger">Critical</span>
<span class="badge badge-system">System</span>
<span class="badge badge-info">72</span>
\`\`\`
### Icon Badges
Combine badges with icons using .c8y-icon-badge wrapper:

\`\`\`html
<span class="c8y-icon-badge" title="14 Critical alarms">
  <i class="dlt-c8y-icon-exclamation-circle status critical"></i>
  <span class="badge badge-danger" aria-live="assertive">14</span>
</span>
\`\`\`

## Loading Spinner
Shows content is being loaded or processed:

\`\`\`html
<div class="spinner">
  <div class="rect1"></div>
  <div class="rect2"></div>
  <div class="rect3"></div>
  <div class="rect4"></div>
  <div class="rect5"></div>
</div>
\`\`\`

## Tag
Tags highlight small pieces of information inline. They are commonly used to display categories, filters, or selected options in a visually appealing and compact manner.

Add the .tag class to any <span> or <div> together with any of the modifier classes mentioned below to change the appearance of an inline label. Add the .font-size-inherit class to inherit the font size.

\`\`\`html
<h1>heading 1
<span class="tag tag--default">Default</span>
</h1>
<br>
<h2>heading 2
<span class="tag tag--primary">Primary</span>
</h2>
<br>
<h3>heading 3
<span class="tag tag--danger">Danger</span>
</h3>
<br>
<h4>heading 4
<span class="tag tag--success font-size-inherit">Success</span>
</h4>
<br>
<h5>heading 5
<span class="tag tag--warning">Warning</span>
</h5>
<br>
<h6>heading 6
<span class="tag tag--info">Info</span>
</h6>
\`\`\`

## Table
Tables help you see and process great amounts of data in a tabular form. Designed for simplicity and clarity, they are an efficient way to organize and present information.


### Default table

For basic styling—light padding and only horizontal dividers—add the base class .table to any table tag. It may seem redundant, but given the widespread use of tables for other plugins like calendars and date pickers, we have opted to isolate our custom table styles.

\`\`\`html
<div class="container-fluid">
  <table class="table" role="table" aria-label="Basic data table">
    <caption>Optional table caption.</caption>
    <colgroup>
      <col width="20px">
      <col width="33%">
      <col width="33%">
      <col width="33%">
    </colgroup>
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">First Name</th>
        <th scope="col">Last Name</th>
        <th scope="col">Username</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">1</th>
        <td>Mark</td>
        <td>Field</td>
        <td>mod22755</td>
      </tr>
      <tr>
        <th scope="row">2</th>
        <td>Jacob</td>
        <td>Diom</td>
        <td>2weet22</td>
      </tr>
      <tr>
        <th scope="row">3</th>
        <td>Larry</td>
        <td>the Clam</td>
        <td>art36552</td>
      </tr>
    </tbody>
  </table>
</div>
\`\`\`

### Striped rows
Use .table-striped to add zebra-striping to any table row within the tbody tag.

\`\`\`html
<div class="container-fluid">
  <table class="table table-striped" role="table" aria-label="Striped data table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">First Name</th>
        <th scope="col">Last Name</th>
        <th scope="col">Username</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">1</th>
        <td>Mark</td>
        <td>Field</td>
        <td>mod22755</td>
      </tr>
      <tr>
        <th scope="row">2</th>
        <td>Jacob</td>
        <td>Diom</td>
        <td>2weet22</td>
      </tr>
      <tr>
        <th scope="row">3</th>
        <td>Larry</td>
        <td>the Clam</td>
        <td>art36552</td>
      </tr>
    </tbody>
  </table>
</div>
\`\`\`

### Bordered tables
Add .table-bordered for borders on all sides of the table and cells.

\`\`\`html
<div class="container-fluid">
  <table class="table table-bordered" role="table" aria-label="Bordered data table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">First Name</th>
        <th scope="col">Last Name</th>
        <th scope="col">Username</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">1</th>
        <td>Mark</td>
        <td>Field</td>
        <td>mod22755</td>
      </tr>
      <tr>
        <th scope="row">2</th>
        <td>Jacob</td>
        <td>Diom</td>
        <td>2weet22</td>
      </tr>
      <tr>
        <th scope="row">3</th>
        <td>Larry</td>
        <td>the Clam</td>
        <td>art36552</td>
      </tr>
    </tbody>
  </table>
</div>
\`\`\`


### Hover rows
Add .table-hover to enable a hover state on table rows within a tbody tag.

\`\`\`html
<div class="container-fluid">
  <table class="table table-hover" role="table" aria-label="Hoverable data table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">First Name</th>
        <th scope="col">Last Name</th>
        <th scope="col">Username</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">1</th>
        <td>Mark</td>
        <td>Field</td>
        <td>mod22755</td>
      </tr>
      <tr>
        <th scope="row">2</th>
        <td>Jacob</td>
        <td>Diom</td>
        <td>2weet22</td>
      </tr>
      <tr>
        <th scope="row">3</th>
        <td>Larry</td>
        <td>the Clam</td>
        <td>art36552</td>
      </tr>
    </tbody>
  </table>
</div>
\`\`\`


### Condensed tables
When in need of showing tables in a more compact way, add .table-condensed to reduce font size and cut cell padding in half.

\`\`\`html
<div class="container-fluid">
  <table class="table table-condensed" role="table" aria-label="Condensed data table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">First Name</th>
        <th scope="col">Last Name</th>
        <th scope="col">Username</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">1</th>
        <td>Mark</td>
        <td>Field</td>
        <td>mod22755</td>
      </tr>
      <tr>
        <th scope="row">2</th>
        <td>Jacob</td>
        <td>Diom</td>
        <td>2weet22</td>
      </tr>
      <tr>
        <th scope="row">3</th>
        <td colspan="2">Larry the Clam</td>
        <td>art36552</td>
      </tr>
    </tbody>
  </table>
</div>
\`\`\`

## Alarms
Alarms indicate device or system issues with varying levels of severity. Each alarm has both a severity level and a status to track its lifecycle.

### Alarm Severities

Alarms are classified into four severity levels, each with its own icon and use case:

- **CRITICAL**: Device is out of service and requires immediate attention
- **MAJOR**: Device has a significant problem that should be fixed
- **MINOR**: Device has a problem that may need attention
- **WARNING**: Informational warning that should be noted

\`\`\`html
<!-- Critical Alarm -->
<i class="status stroked-icon c8y-icon dlt-c8y-icon-exclamation-circle critical"></i>
<span>Critical: System failure detected</span>

<!-- Major Alarm -->
<i class="status stroked-icon c8y-icon dlt-c8y-icon-warning major"></i>
<span>Major: Service degradation</span>

<!-- Minor Alarm -->
<i class="status stroked-icon c8y-icon dlt-c8y-icon-high-priority minor"></i>
<span>Minor: Performance threshold exceeded</span>

<!-- Warning Alarm -->
<i class="status stroked-icon c8y-icon dlt-c8y-icon-circle warning"></i>
<span>Warning: Maintenance required soon</span>

### Alarm Statuses
Alarms progress through three possible statuses during their lifecycle:

- Active: Alarm has been raised and no one is currently addressing it
- Acknowledged: Someone has acknowledged the alarm and is working on resolution
- Cleared: The issue has been resolved (either manually cleared or auto-resolved by the device)

\`\`\`html
<!-- Active Status -->
<i class="c8y-icon dlt-c8y-icon-bell"></i>
<span>Active alarm</span>

<!-- Acknowledged Status -->
<i class="c8y-icon dlt-c8y-icon-bell-slash"></i>
<span>Acknowledged by technician</span>

<!-- Cleared Status -->
<i class="c8y-icon c8y-icon-alert-idle"></i>
<span>Alarm cleared</span>
\`\`\`\``;
const HTML_WIDGET_AGENT = {
    snapshot: __MODE__ !== 'production',
    label: gettext('HTML Widget Code assistant'),
    definitions: [
        {
            name: 'c8y-html-widget',
            agent: {
                system: `1. **Analyze the user request**
   - Extract specific data requirements
   - Identify visualization needs
   - Note any context dependencies

2. **API Verification**
   - Use the "cumulocity-api-request" tool to verify needed APIs
   - Document the exact API endpoints, parameters, and expected responses

3. **Coding**
   - Put out one code block with only the code, wrap it in a <${EXTRACT_TAG_NAME}> block
   - IMPORTANT: And no other text or markdown formatting inside the <${EXTRACT_TAG_NAME}> block
   - build the widget code using the following rules: ${WIDGET_CODE_INSTRUCTIONS}

4. **Quality Validation**
   - Analyze if the widget fulfills the user request
   - Check for mock data usage vs real API integration
   - If inadequate, ask user for specific clarifications needed
`,
                maxOutputTokens: 20000
            },
            type: 'text',
            mcp: [
                {
                    serverName: 'cumulocity-default',
                    tools: ['cumulocity-api-request']
                }
            ]
        }
    ]
};

class AIHtmlWidgetConfigFactory {
    constructor() {
        this.betaPreviewService = inject(PreviewService);
        this.aiService = inject(AIService);
        this.aiWidgetConfigDefinition = {
            widgetId: defaultWidgetIds.HTML,
            label: gettext('AI Code Assistant'),
            loadComponent: () => import('@c8y/ngx-components/ai/agent-chat').then(m => m.WidgetAiChatSectionComponent),
            initialState: {
                agent: HTML_WIDGET_AGENT,
                title: gettext('I’m your AI Code Assistant, here to help you build powerful widgets for your dashboard.'),
                welcomeText: gettext('Describe the widget you want or select one of the options below to get started.'),
                loadRenderStepComponent: () => import('@c8y/ngx-components/widgets/implementations/html-widget').then(m => m.HtmlAiChatFeedbackComponent),
                suggestions: [
                    {
                        label: gettext('Measurement widget'),
                        prompt: gettext('Create a widget that shows the current measurement of this device.')
                    },
                    {
                        label: gettext('Device status widget'),
                        prompt: gettext('Create a widget that shows the status of my devices.')
                    },
                    {
                        label: gettext('Critical alarm widget'),
                        prompt: gettext('Create a widget that shows all critical alarms.')
                    }
                ]
            },
            priority: 100
        };
    }
    get() {
        return combineLatest([
            from(this.aiService.getAgentHealth(HTML_WIDGET_AGENT.definitions[0].name)),
            this.betaPreviewService.getState$('ui.html-widget.v2').pipe(first())
        ]).pipe(map(([aiExists, state]) => {
            const shouldIncludeAi = aiExists.exists || aiExists.isProviderConfigured;
            if (state && shouldIncludeAi) {
                return [this.aiWidgetConfigDefinition];
            }
            return [];
        }));
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AIHtmlWidgetConfigFactory, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AIHtmlWidgetConfigFactory, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AIHtmlWidgetConfigFactory, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }] });

const htmlWidgetAIChatProviders = [hookWidgetConfig(AIHtmlWidgetConfigFactory)];

/**
 * Generated bundle index. Do not edit.
 */

export { htmlWidgetAIChatProviders };
//# sourceMappingURL=c8y-ngx-components-widgets-definitions-html-widget-ai-config.mjs.map
