const path = require("path");
const { execFileSync } = require("child_process");
const tl = require("azure-pipelines-task-lib/task");

function runScript(scriptName, args = [], extraEnv = {}) {
  const scriptPath = path.join(__dirname, "scripts", scriptName);

  execFileSync("bash", [scriptPath, ...args], {
    stdio: "inherit",
    env: {
      ...process.env,
      ...extraEnv,
    },
  });
}

function generateSonarToken() {
  const response = execFileSync(
    "bash",
    [
      "-c",
      `curl -s -f -u admin:admin -X POST "http://localhost:9000/api/user_tokens/generate" -d "name=ci-token-$(date +%s)"`,
    ],
    { encoding: "utf8" },
  );

  const parsed = JSON.parse(response);
  const token = parsed.token;

  if (!token) {
    throw new Error(`Failed to generate Sonar token. Response: ${response}`);
  }

  return token;
}

async function run() {
  let sonarToken = "";

  try {
    const teamId = tl.getInput("teamId", true);
    const installationId = tl.getInput("installationId", true);
    const projectKey = tl.getInput("projectKey", true);
    const CODEGUARD_API_BASE_URL_EXT =
      process.env.CODEGUARD_API_BASE_URL_EXT || "https://apis.codeguard-stg.fridaplatform.online";
    const DEFAULT_RULES_API_URL = `${CODEGUARD_API_BASE_URL_EXT}/Teams-getSonarRules`;
    const inputRulesApiUrl = tl.getInput("rulesApiUrl", false);
    const rulesApiUrl =
      inputRulesApiUrl && inputRulesApiUrl !== "undefined" && !inputRulesApiUrl.startsWith("undefined/")
        ? inputRulesApiUrl
        : DEFAULT_RULES_API_URL;
    const sources = tl.getInput("sources", false) || "/usr/src";
    const exclusions =
      tl.getInput("exclusions", false) || "**/node_modules/**,**/dist/**,**/build/**,**/__pycache__/**";
    const enforceQualityGate = tl.getBoolInput("enforceQualityGate", false);

    runScript("start-sonar.sh");
    runScript("wait-sonar.sh");

    sonarToken = generateSonarToken();
    tl.setSecret(sonarToken);

    const env = {
      SONAR_TOKEN: sonarToken,
    };

    runScript("fetch-rules.sh", [teamId, installationId, rulesApiUrl], env);
    runScript("configure-profiles.sh", [], env);
    runScript("run-scanner.sh", [projectKey, sources, exclusions], env);
    runScript("extract-issues.sh", [projectKey], env);
    runScript("filter-new-code-issues.sh", [], env);
    runScript("generate-summary.sh", [], env);

    if (enforceQualityGate) {
      runScript("quality-gate.sh", [projectKey], env);
    }

    tl.uploadArtifact("sonar-analysis-results", path.join(process.cwd(), "sonar-results"), "sonar-analysis-results");

    tl.setResult(tl.TaskResult.Succeeded, "CodeGuard SonarQube analysis completed");
  } catch (err) {
    tl.setResult(tl.TaskResult.Failed, err.message);
  } finally {
    try {
      runScript("cleanup.sh");
    } catch (_) {}
  }
}

run();
