const path = require('node:path');
const fs = require('fs-extra');
const { readBundleId } = require('./apple-release');

/**
 * Reads the Android applicationId (package name) of the project.
 * Source of truth is build.gradle(.kts) — what gets baked into the APK and
 * what the device sees. kit_setup.json can drift when the user renames the
 * package manually after `kasy new`, so it's only used as a fallback when
 * the Android project hasn't been generated yet.
 */
async function readPackageName(projectDir) {
  const candidates = [
    path.join(projectDir, 'android', 'app', 'build.gradle.kts'),
    path.join(projectDir, 'android', 'app', 'build.gradle'),
  ];
  for (const file of candidates) {
    if (!(await fs.pathExists(file))) continue;
    const content = await fs.readFile(file, 'utf8');
    const m = content.match(/applicationId\s*=?\s*["']([^"']+)["']/);
    if (m) return m[1];
  }
  const kitSetupPath = path.join(projectDir, 'kit_setup.json');
  if (await fs.pathExists(kitSetupPath)) {
    try {
      const kit = await fs.readJson(kitSetupPath);
      if (kit.bundleId) return kit.bundleId;
    } catch {
      // ignore
    }
  }
  return null;
}

module.exports = { readBundleId, readPackageName };
