import type {Grove as GroveType} from "./Grove";
import type {TreeNode} from "./TreeNode";
import {useNodesStore} from "./store";
import {useEffect, useState} from "react";

// Lazy loaded Grove module to avoid circular dependency
let GroveModule: typeof GroveType | null = null;
const getGroveModule = async () => {
    if (!GroveModule) {
        const module = await import('./Grove');
        GroveModule = module.Grove;
    }
    return GroveModule;
};

/**
 * Gets the suggestedScope from the root tree node for a given testable ID.
 * Uses lazy loading of Grove to avoid circular dependencies.
 */
export const getSuggestedScopeForTestable = async (testableId: string): Promise<TreeNode['suggestedScope'] | undefined> => {
    const Grove = await getGroveModule();
    const store = useNodesStore.getState();
    const {grove, testables} = Grove.fromState(store, true);
    const rootTestable = testables.getRootNode(testableId);
    const testableCompositeNode = grove.get(rootTestable?.id) as { getTreeNode?: () => TreeNode } | undefined;
    return testableCompositeNode?.getTreeNode?.()?.suggestedScope;
};

export const useSuggestedScopeForTestableId = (testableId: string) => {
    const [suggestedScope, setSuggestedScope] = useState<TreeNode['suggestedScope']>(undefined);

    useEffect(() => {
        let isMounted = true;
        getSuggestedScopeForTestable(testableId).then((scope) => {
            if (isMounted) {
                setSuggestedScope(scope);
            }
        });
        return () => { isMounted = false; };
    }, [testableId]);

    return suggestedScope;
}
