/*
 Copyright (C) 2026 3NSoft Inc.

 This program is free software: you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation, either version 3 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 this program. If not, see <http://www.gnu.org/licenses/>.
*/

import type { CmdsHandler } from "../caps/shell/cmd-invocation";
import type { GetAppFSResourceFor } from "../caps/shell/fs-resource";

type RPCConnection = web3n.rpc.client.RPCConnection;
type CommonDef = web3n.caps.CommonComponentSetting;
type WritableFS = web3n.files.WritableFS;
type Runtime = web3n.caps.Runtime;
type CmdParams = web3n.shell.commands.CmdParams;
type SystemMonitor = web3n.system.monitor.SystemMonitor;
type OpenConnectionInfo = web3n.system.monitor.OpenConnectionInfo;
type PostInstallState =web3n.system.apps.PostInstallState;

export interface Component {
	readonly runtime: CommonDef['runtime'];
	readonly domain: string;
	readonly entrypoint: string;
	start(): Promise<void>;
	setCloseListener(onClose: () => void): void;
	close(): void;
	addService(name: string, service: Service): void;
	getService(name: string): Promise<Service>;
	listServiceConnections(): OpenConnectionInfo[]|undefined;
	readonly stdOut: NodeJS.ReadableStream;
	readonly stdErr: NodeJS.ReadableStream;
}

export interface GUIComponent extends Component {
	setCmdHandler: (handler: CmdsHandler) => void;
}

export interface Service {

	canHandleCall(): boolean;

	ensureCallerAllowed(callerApp: string, callerComponent: string): void;

	connect(callerApp: string, callerComponent: string): Promise<{
		connection: RPCConnection;
		doOnClose: (cleanup: ()=>void) => void;
	}>;

	listOpenConnections(entrypoint: string): OpenConnectionInfo[];

}

type W3N = web3n.caps.W3N;
type SitesW3N = web3n.caps.sites.W3N;

export interface AppCAPsAndSetup {
	w3n: W3N;
	close: () => void;
	setApp: AppSetter;
}

export interface SiteCAPsAndSetup {
	w3n: SitesW3N;
}

export type AppSetter = (app: Component) => void;

export interface CAPsSetupFns {
	close?: () => void;
	setApp?: AppSetter;
}

export function makeCAPsSetAppAndCloseFns(...fns: (CAPsSetupFns|undefined)[]): {
	close: () => void; setApp: AppSetter;
} {
	const closeFns: (() => void)[] = [];
	const setAppFns: AppSetter[] = [];
	for (const setupFns of fns) {
		if (setupFns) {
			const { close, setApp } = setupFns;
			if (close) {
				closeFns.push(close);
			}
			if (setApp) {
				setAppFns.push(setApp);
			}
		}
	}
	return {
		close: ((closeFns.length > 0) ?
			() => {
				try {
					for (const closeFn of closeFns) {
						closeFn();
					}
				} catch (err) {
					console.error(err);
				}
			} :
			noop
		),
		setApp: ((setAppFns.length > 0) ?
			app => {
				for (const setApp of setAppFns) {
					setApp(app);
				}
			} :
			noop
		)
	};
}

function noop() {}

export type GetAppStorage = (type: 'local'|'synced') => Promise<WritableFS>;

export interface App {

	handleCmd(cmd: CmdParams, callerApp: string, callerComponent: string): Promise<void>;

	handleCmdFromUser(cmd: CmdParams): Promise<void>;

	launchWebGUI(entrypoint: string, devTools: boolean): Promise<void>;

	launchFormFactorAppropriateWebGUI(devTools: boolean): Promise<void>;

	loadOnStartup(): Promise<void>;

	getServiceToHandleCall(caller: Component, service: string): Promise<Service>;

	get version(): string;

	get appId(): string;

	updateTitlesOnGUIComponents(): void;

	get isClosed(): boolean;

	stopAndClose(): Promise<void>;

	exposedFSResource(
		resourceName: string, requestingApp: string, requestingComponent: string
	): ReturnType<GetAppFSResourceFor>;

	/**
	 * Info list of open instances of this app's components.
	 */
	get openInstances(): {
		entrypoint: string; runtime: Runtime; numOfInstances: number;
	}[];

	/**
	 * Info list of open connection to this app's services.
	 * If this app has no exposed services, undefined is returned.
	 */
	get openSrvConnections(): OpenConnectionInfo[]|undefined;

}

export interface LiveApps {

	get(appId: string, devTools: boolean): Promise<App>;

	updateWindowTitles(): void;

	closeAppToUninstall(appDomain: string): Promise<void>;

	stopAndCloseAllApps(): Promise<void>;

	closeAppsAfterUpdate(idsOfAppsToClose: string[]): Promise<void>;

	followupAppInstall(appId: string, version: string): PostInstallState;

	makeMonitor(): SystemMonitor;

}
