/*
 * Copyright (c) 2026 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as fs from 'fs';
import * as path from 'path';
import * as ini from 'ini';

// This context key controls whether the Cangjie extension's Build icon is visible:
// set it to true to show the icon and false to hide it.
export const cangjieBuildContextKey = 'cangjie.showBuildToolBar';

// This context key indicates whether the current workspace is a CJMP project:
// set it to true for a CJMP project and false otherwise.
export const cjmpProjectContextKey = 'cjmp.isCjmpProject';

export interface WorkspaceFolderLocation {
  uri: {
    fsPath: string;
  };
}

/**
 * Returns whether a parsed project.conf contains a non-empty project type.
 */
export function isValidCjmpProjectConfig(projectConfiguration: unknown): boolean {
  if (!projectConfiguration || typeof projectConfiguration !== 'object') {
    return false;
  }

  const projectSection = (projectConfiguration as Record<string, unknown>).project;
  if (!projectSection || typeof projectSection !== 'object') {
    return false;
  }

  const projectType = (projectSection as Record<string, unknown>).type;
  return typeof projectType === 'string' && projectType.trim().length > 0;
}

/**
 * Returns the first workspace folder when its root contains a valid CJMP project configuration.
 * The CJMP extension currently supports a single workspace folder.
 */
export function getCjmpProjectWorkspaceFolder(
  workspaceFolders: readonly WorkspaceFolderLocation[] | undefined,
): WorkspaceFolderLocation | undefined {
  const workspaceFolder = workspaceFolders?.[0];
  if (!workspaceFolder) {
    return undefined;
  }

  const projectConfigurationPath = path.join(workspaceFolder.uri.fsPath, 'project.conf');
  try {
    if (!fs.existsSync(projectConfigurationPath)) {
      return undefined;
    }

    const projectConfiguration = ini.parse(fs.readFileSync(projectConfigurationPath, 'utf8'));
    if (!isValidCjmpProjectConfig(projectConfiguration)) {
      return undefined;
    }
  } catch {
    return undefined;
  }

  return workspaceFolder;
}