import type { ProjectSessionState } from "@qjclaw/shared-types";
import type { ProjectIntentRoute, ProjectIntentRouterService } from "./project-intent-router.js";
import type { ProjectStoreService } from "./project-store.js";

const BUILTIN_HOME_PROJECT_ID = "home-chat";

export interface ResolvedProjectChatTarget {
  sessionState: ProjectSessionState;
  route: ProjectIntentRoute | null;
  autoRouted: boolean;
  previousProjectId: string;
}

export class ProjectChatTargetResolverService {
  private readonly projectStore: ProjectStoreService;
  private readonly projectIntentRouter: ProjectIntentRouterService;

  constructor(projectStore: ProjectStoreService, projectIntentRouter: ProjectIntentRouterService) {
    this.projectStore = projectStore;
    this.projectIntentRouter = projectIntentRouter;
  }

  async resolve(sessionId: string, prompt: string, selectedSkillId?: string | null): Promise<ResolvedProjectChatTarget> {
    const sessionState = await this.projectStore.getSessionState(sessionId);
    const selectedSkill = selectedSkillId?.trim() || null;
    void prompt;

    if (selectedSkill || sessionState.projectId !== BUILTIN_HOME_PROJECT_ID) {
      return {
        sessionState,
        route: null,
        autoRouted: false,
        previousProjectId: sessionState.projectId
      };
    }

    return {
      sessionState,
      route: null,
      autoRouted: false,
      previousProjectId: sessionState.projectId
    };
  }

  async resolveIntentSuggestion(prompt: string, currentProjectId?: string | null): Promise<ProjectIntentRoute | null> {
    const normalizedCurrentProjectId = currentProjectId?.trim() || BUILTIN_HOME_PROJECT_ID;
    const route = await this.projectIntentRouter.resolve(prompt, normalizedCurrentProjectId);
    if (!route || route.projectId === BUILTIN_HOME_PROJECT_ID || route.projectId === normalizedCurrentProjectId) {
      return null;
    }

    return route;
  }
}
