import { JupyterFrontEnd, LabShell } from "@jupyterlab/application";
import { TOGGLE_AI_CHAT_MESSAGE } from "../constants";
import { Panel } from "@lumino/widgets";
import { getSMEnvironmentMetadata } from '../utils';


export class IngressPointService {
    private validDomainRegEx: RegExp | undefined;
    
    constructor(private app: JupyterFrontEnd, private chatPanel: Panel) {
        // Initialize origin validation asynchronously
        this.initializeOriginValidation().catch(e => {
            console.error('Failed to initialize origin validation for IngressPointService:', e);
        });
    }
    
    private async initializeOriginValidation(): Promise<void> {
        try {
            const { domain_id, aws_region, dz_stage, sm_domain_id } = 
                await getSMEnvironmentMetadata();
            
            const stage = dz_stage === 'prod' ? '' : `-${dz_stage}`;
            const patterns: string[] = [];
            
            if (domain_id) {
                patterns.push(`^https://${domain_id}\\.sagemaker${stage}\\.${aws_region}\\.on\\.aws$`);
            }
            if (sm_domain_id && sm_domain_id !== domain_id) {
                patterns.push(`^https://${sm_domain_id}\\.sagemaker${stage}\\.${aws_region}\\.on\\.aws$`);
            }
            
            if (patterns.length > 0) {
                this.validDomainRegEx = new RegExp(patterns.join('|'));
                console.log('IngressPointService: Initialized origin validation with dynamic patterns');
            }
        } catch (e) {
            console.error('IngressPointService: Failed to fetch SM environment metadata for origin validation:', e);
            // Continue without regex - will fall back to same-origin only
        }
    }

    public async initialize(){
        window.addEventListener('message', this.messageListener);
    }

    private messageListener = async (event: MessageEvent): Promise<void> => {
        if(!this.isMessageOriginValid(event)) return;

        /**
         * When a Q toggle event is passed into the iframe from the parent,
         * this toggles visibility of the Q chat window.
         */
        if (event.data === TOGGLE_AI_CHAT_MESSAGE) {
            this.toggleQChat(this.app, this.chatPanel);
            return;
        }
    }

    private isMessageOriginValid(event: MessageEvent): boolean {
        // Use dynamic regex if available (matches webview.ts approach)
        if (this.validDomainRegEx) {
            const isValid = this.validDomainRegEx.test(event.origin) || 
                           event.origin === window.location.origin;
            
            if (!isValid) {
                console.warn('IngressPointService: Rejected message from untrusted origin:', event.origin);
            }
            
            return isValid;
        }
        
        // Fallback: same-origin only (most restrictive)
        const isValid = event.origin === window.location.origin;
        
        if (!isValid) {
            console.warn('IngressPointService: Origin validation using fallback - rejected:', event.origin);
        }
        
        return isValid;
    }

    private toggleQChat(app: JupyterFrontEnd, chatPanel: Panel): void {
        const chatPanelId = chatPanel.id;

        if(!chatPanelId){
            throw new Error("Chat widget not found.")
        }
        if (app.shell instanceof LabShell) {
        const leftWidgets = Array.from(app.shell.widgets('left'));
        const rightWidgets = Array.from(app.shell.widgets('right'));
        // support finding widgets on left or right panel
        const widgets = [...leftWidgets, ...rightWidgets];
        const chatWidget = widgets.find((widget) => widget.id === chatPanelId);

        if (chatWidget) {
            if (chatWidget.isHidden) {
            app.shell.activateById(chatPanelId);
            } else {
            if (rightWidgets.find((widget) => widget.id === chatPanelId)) {
                app.shell.collapseRight();
            } else {
                app.shell.collapseLeft();
            }
            }
        }
        }
    }
}