@attribute [Route(Routes.ASSISTANT_DOCUMENT_ANALYSIS)]
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.NoSettingsPanel>
@using AIStudio.Settings
@using AIStudio.Settings.DataModel

<div class="mb-6"></div>

<MudText Typo="Typo.h4" Class="mb-3">
    @T("Document analysis policies")
</MudText>

<MudJustifiedText Typo="Typo.body1" Class="mb-3">
    @T("Here you have the option to save different policies for various document analysis assistants and switch between them.")
</MudJustifiedText>

@if(this.SettingsManager.ConfigurationData.DocumentAnalysis.Policies.Count is 0)
{
    <MudText Typo="Typo.body1" Class="mb-3">
        @T("You have not yet added any document analysis policies.")
    </MudText>
}
else
{
    <MudList Disabled="@this.ArePolicyControlsDisabled" Color="Color.Primary" T="DataDocumentAnalysisPolicy" Class="mb-1" SelectedValue="@this.selectedPolicy" SelectedValueChanged="@this.SelectedPolicyChanged">
        @foreach (var policy in this.SettingsManager.ConfigurationData.DocumentAnalysis.Policies)
        {
            @if (policy.IsEnterpriseConfiguration)
            {
                <MudListItem T="DataDocumentAnalysisPolicy" Icon="@Icons.Material.Filled.Policy" Value="@policy">
                    @policy.PolicyName
                    <MudTooltip Text="@T("This policy is managed by your organization.")" Placement="Placement.Right">
                        <MudIcon Icon="@Icons.Material.Filled.Business" Size="Size.Small" Class="ml-2" Style="vertical-align: middle;" />
                    </MudTooltip>
                </MudListItem>
            }
            else
            {
                <MudListItem T="DataDocumentAnalysisPolicy" Icon="@Icons.Material.Filled.Policy" Value="@policy">
                    @policy.PolicyName
                </MudListItem>
            }
        }
    </MudList>
}

<MudStack Row="@true" Class="mt-1">
    <MudButton OnClick="@this.AddPolicy" Disabled="@this.ArePolicyControlsDisabled" Variant="Variant.Filled" Color="Color.Primary">
        @T("Add policy")
    </MudButton>
    <MudButton OnClick="@this.RemovePolicy" Disabled="@(this.ArePolicyControlsDisabled || (this.selectedPolicy?.IsProtected ?? true) || (this.selectedPolicy?.IsEnterpriseConfiguration ?? true))" Variant="Variant.Filled" Color="Color.Error">
        @T("Delete this policy")
    </MudButton>
</MudStack>

<MudDivider Style="height: 0.25ch; margin: 1rem 0;" Class="mt-6" />

@if ((this.selectedPolicy?.HidePolicyDefinition ?? false) && (this.selectedPolicy?.IsEnterpriseConfiguration ?? false))
{
    @* When HidePolicyDefinition is true AND the policy is an enterprise configuration, show only the document selection section without expansion panels *@
    <div class="mb-3 mt-3">
        <MudText Typo="Typo.h5" Class="mb-3">
            @T("Document selection - Policy"): @this.selectedPolicy?.PolicyName
        </MudText>

        <MudText Typo="Typo.h6" Class="mb-1">
            @T("Policy Description")
        </MudText>

        <MudJustifiedText Typo="Typo.body1" Class="mb-3">
            @this.selectedPolicy?.PolicyDescription
        </MudJustifiedText>

        <MudText Typo="Typo.h6" Class="mb-1 mt-6">
            @T("Documents for the analysis")
        </MudText>

        <AttachDocuments Name="Document Analysis Files" Layer="@DropLayers.ASSISTANTS" @bind-DocumentPaths="@this.loadedDocumentPaths" CatchAllDocuments="true" UseSmallForm="false" Provider="@this.ProviderSettings"/>
    </div>
}
else
{
    @* Standard view with expansion panels *@
    <MudExpansionPanels Class="mb-3 mt-3" MultiExpansion="@false">
        <ExpansionPanel HeaderIcon="@Icons.Material.Filled.Policy" HeaderText="@(T("Policy definition") + $": {this.selectedPolicy?.PolicyName}")" IsExpanded="@this.policyDefinitionExpanded" ExpandedChanged="@this.PolicyDefinitionExpandedChanged">
            @if (!this.policyDefinitionExpanded)
            {
                <MudJustifiedText Typo="Typo.body1" Class="mb-1">
                    @T("Expand this section to view and edit the policy definition.")
                </MudJustifiedText>
            }
            else
            {
                <MudText Typo="Typo.h5" Class="mb-1">
                    @T("Common settings")
                </MudText>

                <MudTextField T="string" Disabled="@this.IsNoPolicySelectedOrProtected" @bind-Text="@this.policyName" Validation="@this.ValidatePolicyName" Immediate="@true" Label="@T("Policy name")" HelperText="@T("Please give your policy a name that provides information about the intended purpose. The name will be displayed to users in AI Studio.")" Counter="60" MaxLength="60" Variant="Variant.Outlined" Margin="Margin.Normal" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3" OnKeyUp="@(() => this.PolicyNameWasChanged())"/>

                <MudTextField T="string" Disabled="@this.IsNoPolicySelectedOrProtected" @bind-Text="@this.policyDescription" Validation="@this.ValidatePolicyDescription" Immediate="@true" Label="@T("Policy description")" HelperText="@T("Please provide a brief description of your policy. Describe or explain what your policy does. This description will be shown to users in AI Studio.")" Counter="512" MaxLength="512" Variant="Variant.Outlined" Margin="Margin.Normal" Lines="3" AutoGrow="@true" MaxLines="6" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
                
                <MudTextSwitch Disabled="@this.IsNoPolicySelectedOrProtected" Label="@T("Hide the policy definition when distributed via configuration plugin?")" Value="@this.policyHidePolicyDefinition" ValueChanged="async state => await this.PolicyHidePolicyDefinitionWasChanged(state)" LabelOn="@T("Yes, hide the policy definition")" LabelOff="@T("No, show the policy definition")" />

                <MudJustifiedText Typo="Typo.body2" Class="mt-2 mb-3">
                    @T("Note: This setting only takes effect when this policy is exported and distributed via a configuration plugin to other users. When enabled, users will only see the document selection interface and cannot view or modify the policy details. This setting does NOT affect your local view - you will always see the full policy definition for policies you create.")
                </MudJustifiedText>

                <ConfigurationMinConfidenceSelection Disabled="@(() => this.IsNoPolicySelectedOrProtected)" RestrictToGlobalMinimumConfidence="true" SelectedValue="@(() => this.policyMinimumProviderConfidence)" SelectionUpdateAsync="@(async level => await this.PolicyMinimumConfidenceWasChangedAsync(level))" />

                <ConfigurationProviderSelection Component="Components.DOCUMENT_ANALYSIS_ASSISTANT" Data="@this.availableLLMProviders" Disabled="@(() => this.IsNoPolicySelectedOrProtected)" SelectedValue="@(() => this.policyPreselectedProviderId)" SelectionUpdate="@(providerId => this.PolicyPreselectedProviderWasChanged(providerId))" ExplicitMinimumConfidence="@this.GetPolicyMinimumConfidenceLevel()"/>

                <ConfigurationSelect OptionDescription="@T("Preselect a profile")" Disabled="@(() => this.IsNoPolicySelected)" SelectedValue="@(() => this.policyPreselectedProfile)" Data="@ConfigurationSelectDataFactory.GetComponentProfilesData(this.SettingsManager.ConfigurationData.Profiles)" SelectionUpdateAsync="@(async selection => await this.PolicyPreselectedProfileWasChangedAsync(selection))" OptionHelp="@T("Choose whether the policy should use the app default profile, no profile, or a specific profile.")"/>

                <MudTextSwitch Disabled="@(this.IsNoPolicySelected || (this.selectedPolicy?.IsEnterpriseConfiguration ?? true))" Label="@T("Would you like to protect this policy so that you cannot accidentally edit or delete it?")" Value="@this.policyIsProtected" ValueChanged="async state => await this.PolicyProtectionWasChanged(state)" LabelOn="@T("Yes, protect this policy")" LabelOff="@T("No, the policy can be edited")" />

                <MudText Typo="Typo.h5" Class="mt-6 mb-1">
                    @T("Analysis and output rules")
                </MudText>

                <MudJustifiedText Typo="Typo.body1" Class="mt-3">
                    @T("Use the analysis and output rules to define how the AI evaluates your documents and formats the results.")
                </MudJustifiedText>

                <MudJustifiedText Typo="Typo.body1" Class="mt-3">
                    @T("The analysis rules specify what the AI should pay particular attention to while reviewing the documents you provide, and which aspects it should highlight or save. For example, if you want to extract the potential of green hydrogen for agriculture from a variety of general publications, you can explicitly define this in the analysis rules.")
                </MudJustifiedText>

                <MudTextField T="string" Disabled="@this.IsNoPolicySelectedOrProtected" @bind-Text="@this.policyAnalysisRules" Validation="@this.ValidateAnalysisRules" Immediate="@true" Label="@T("Analysis rules")" HelperText="@T("Please provide a description of your analysis rules. This rules will be used to instruct the AI on how to analyze the documents.")" Variant="Variant.Outlined" Margin="Margin.Normal" Lines="5" AutoGrow="@true" MaxLines="26" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>

                <ReadFileContent Text="@T("Load analysis rules from document")" @bind-FileContent="@this.policyAnalysisRules" Disabled="@this.IsNoPolicySelectedOrProtected"/>

                <MudJustifiedText Typo="Typo.body1" Class="mt-3">
                    @T("After the AI has processed all documents, it needs your instructions on how the result should be formatted. Would you like a structured list with keywords or a continuous text? Should the output include emojis or be written in formal business language? You can specify all these preferences in the output rules. There, you can also predefine a desired structure—for example, by using Markdown formatting to define headings, paragraphs, or bullet points.")
                </MudJustifiedText>

                <MudTextField T="string" Disabled="@this.IsNoPolicySelectedOrProtected" @bind-Text="@this.policyOutputRules" Validation="@this.ValidateOutputRules" Immediate="@true" Label="@T("Output rules")" HelperText="@T("Please provide a description of your output rules. This rules will be used to instruct the AI on how to format the output of the analysis.")" Variant="Variant.Outlined" Margin="Margin.Normal" Lines="5" AutoGrow="@true" MaxLines="26" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>

                <ReadFileContent Text="@T("Load output rules from document")" @bind-FileContent="@this.policyOutputRules" Disabled="@this.IsNoPolicySelectedOrProtected"/>

                @if (this.SettingsManager.ConfigurationData.App.ShowAdminSettings)
                {
                    <MudText Typo="Typo.h5" Class="mt-6 mb-1">
                        @T("Preparation for enterprise distribution")
                    </MudText>

                    <MudButton StartIcon="@Icons.Material.Filled.ContentCopy" Disabled="@(this.IsNoPolicySelected || (this.selectedPolicy?.IsEnterpriseConfiguration ?? false))" Variant="Variant.Filled" Color="Color.Default" OnClick="@this.ExportPolicyAsConfiguration">
                        @T("Export policy as configuration section")
                    </MudButton>
                }
            }
        </ExpansionPanel>

        <MudDivider Style="height: 0.25ch; margin: 1rem 0;" Class="mt-6" />

        <ExpansionPanel HeaderIcon="@Icons.Material.Filled.DocumentScanner" HeaderText="@(T("Document selection - Policy") + $": {this.selectedPolicy?.PolicyName}")" IsExpanded="@(this.selectedPolicy?.IsProtected ?? false)">
            <MudText Typo="Typo.h5" Class="mb-1">
                @T("Policy Description")
            </MudText>

            <MudJustifiedText Typo="Typo.body1" Class="mb-3">
                @this.selectedPolicy?.PolicyDescription
            </MudJustifiedText>

            <MudText Typo="Typo.h5" Class="mb-1 mt-6">
                @T("Documents for the analysis")
            </MudText>

            <AttachDocuments Name="Document Analysis Files" Layer="@DropLayers.ASSISTANTS" @bind-DocumentPaths="@this.loadedDocumentPaths" CatchAllDocuments="true" UseSmallForm="false" Provider="@this.ProviderSettings"/>

        </ExpansionPanel>
    </MudExpansionPanels>
}
    
<ProviderSelection @bind-ProviderSettings="@this.ProviderSettings" ValidateProvider="@this.ValidatingProvider" ExplicitMinimumConfidence="@this.GetPolicyMinimumConfidenceLevel()"/>
