import fs from 'node:fs';
import path3 from 'node:path';
import { execFile, execFileSync, spawn } from 'node:child_process';
import { promisify } from 'node:util';
import { fileURLToPath } from 'node:url';
import 'posthog-node';

// src/features/watch-pr-review/infrastructure/gh.ts
var DEFAULT_POLL_INTERVAL_MS = 1e4;
var DEFAULT_CONCURRENCY = 2;
var DEFAULT_CONFIG = {
  concurrency: DEFAULT_CONCURRENCY,
  pollIntervalMs: DEFAULT_POLL_INTERVAL_MS,
  repos: [{ repo: "owner/repository", enabled: false }]
};
var DEFAULT_HISTORY = { reviewed: [] };
function getWatchPaths(baseDir) {
  const dir = path3.join(baseDir, "watch-pr-review");
  return {
    configPath: path3.join(dir, "repos.json"),
    dir,
    historyPath: path3.join(dir, "history.json"),
    reportsDir: path3.join(dir, "reports")
  };
}
function ensureWatchFiles(watchPaths) {
  fs.mkdirSync(watchPaths.dir, { recursive: true });
  fs.mkdirSync(watchPaths.reportsDir, { recursive: true });
  if (!fs.existsSync(watchPaths.configPath)) {
    fs.writeFileSync(watchPaths.configPath, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}
`, "utf8");
  }
  if (!fs.existsSync(watchPaths.historyPath)) {
    fs.writeFileSync(watchPaths.historyPath, `${JSON.stringify(DEFAULT_HISTORY, null, 2)}
`, "utf8");
  }
}
function openInEditor(filePath) {
  const editor = process.env.VISUAL || process.env.EDITOR;
  if (editor) {
    execFileSync(editor, [filePath], { stdio: "inherit" });
    return;
  }
  const opener = resolvePlatformOpener();
  spawn(opener.command, [...opener.args, filePath], { detached: true, stdio: "ignore" }).unref();
}
function resolvePlatformOpener() {
  if (process.platform === "darwin") {
    return { args: [], command: "open" };
  }
  if (process.platform === "win32") {
    return { args: ["/c", "start", ""], command: "cmd" };
  }
  return { args: [], command: "xdg-open" };
}
var DEFAULT_TOKEN_OPTIMIZER_STATE = {
  enabled: false
};
globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ ?? (globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ = {
  ...DEFAULT_TOKEN_OPTIMIZER_STATE
});
promisify(execFile);

// src/platform/request-security/registry.ts
var securityRegistryState = globalThis.__JUHONG_E_SECURITY_REGISTRY__ ?? (globalThis.__JUHONG_E_SECURITY_REGISTRY__ = {
  patternRules: /* @__PURE__ */ new Map(),
  validatorRules: /* @__PURE__ */ new Map()
});
var GLOBAL_PATTERN_RULES = securityRegistryState.patternRules;
securityRegistryState.validatorRules;
function addGlobalSecurityPattern(rule) {
  GLOBAL_PATTERN_RULES.set(rule.name, rule);
}

// src/platform/request-security/default-rules.ts
var initialized = false;
function formatResidentRegistrationNumber(matchedText) {
  const digits = matchedText.replace(/\D/g, "");
  if (digits.length !== 13) {
    return `${matchedText.slice(0, 3)}***`;
  }
  return `${digits.slice(0, 6)}-${digits[6]}******`;
}
function ensureDefaultSecurityRules() {
  if (initialized) {
    return;
  }
  initialized = true;
  addGlobalSecurityPattern({
    formatMatch: formatResidentRegistrationNumber,
    message: "\uBCF4\uC548 \uC815\uCC45\uC5D0 \uC758\uD574 \uC8FC\uBBFC\uB4F1\uB85D\uBC88\uD638 \uD615\uD0DC\uC758 \uAC12\uC774 \uD3EC\uD568\uB41C \uC785\uB825\uC740 \uC2E4\uD589\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.",
    name: "resident-registration-number",
    pattern: /\b\d{6}[- ]?[1-4]\d{6}\b/
  });
}
var PACKAGE_JSON_FILE_NAME = "package.json";
function findPackageRoot(moduleFilePath) {
  let currentDirectoryPath = path3.dirname(moduleFilePath);
  while (!fs.existsSync(path3.join(currentDirectoryPath, PACKAGE_JSON_FILE_NAME))) {
    const parentDirectoryPath = path3.dirname(currentDirectoryPath);
    if (parentDirectoryPath === currentDirectoryPath) {
      throw new Error(`markdown \uC790\uC0B0 package root\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. start=${moduleFilePath}`);
    }
    currentDirectoryPath = parentDirectoryPath;
  }
  return currentDirectoryPath;
}
function resolvePromptPackageFilePath(importMetaUrl, packageRelativeFilePath) {
  const moduleFilePath = fileURLToPath(importMetaUrl);
  const packageRoot = findPackageRoot(moduleFilePath);
  return path3.normalize(path3.resolve(packageRoot, packageRelativeFilePath));
}
function createPromptMarkdownFileAsset(importMetaUrl, packageRelativeFilePath) {
  return {
    filePath: resolvePromptPackageFilePath(importMetaUrl, packageRelativeFilePath),
    kind: "file-reference"
  };
}
function isPromptMarkdownFileReference(asset) {
  return typeof asset !== "string";
}
function isPromptRuleGroupAsset(asset) {
  return typeof asset !== "string" && !("kind" in asset && asset.kind === "file-reference");
}
function clonePromptMarkdownAsset(asset) {
  return isPromptMarkdownFileReference(asset) ? {
    ...asset,
    filePath: path3.normalize(asset.filePath)
  } : asset;
}

// src/platform/ai-services/stream-output.ts
var DEFAULT_STREAM_OUTPUT_STATE = {
  enabled: false
};
globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ ?? (globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ = {
  ...DEFAULT_STREAM_OUTPUT_STATE
});

// src/platform/prompts/build-common-prompt.ts
createPromptMarkdownFileAsset(
  import.meta.url,
  "src/platform/prompts/assets/common/base-instructions.md"
);

// src/features/watch-pr-review/application/action.ts
function runWatchPrReviewConfigAction(options) {
  const watchPaths = getWatchPaths(options.paths.baseDir);
  ensureWatchFiles(watchPaths);
  console.log(`\u{1F4DD} \uC124\uC815 \uD30C\uC77C\uC744 \uC5FD\uB2C8\uB2E4: ${watchPaths.configPath}`);
  options.trace("watch-pr-review:config:open", watchPaths.configPath);
  try {
    openInEditor(watchPaths.configPath);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.log(`\u26A0\uFE0F  \uC5D0\uB514\uD130\uB85C \uC5F4\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uC9C1\uC811 \uD30C\uC77C\uC744 \uD3B8\uC9D1\uD558\uC138\uC694: ${watchPaths.configPath}
   \uC6D0\uC778: ${message}`);
    options.trace("watch-pr-review:config:open-error", message);
  }
}

// src/platform/runtime-profile.ts
globalThis.__JU_HONG_E_RUNTIME_PROFILE__ ?? (globalThis.__JU_HONG_E_RUNTIME_PROFILE__ = {
  binaryName: "ju-hong-e",
  profile: "all"
});
globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ ?? (globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ = {});

// src/platform/command-runtime/registry.ts
var registryState = globalThis.__JU_HONG_E_COMMAND_REGISTRY__ ?? (globalThis.__JU_HONG_E_COMMAND_REGISTRY__ = {
  juHongECommands: /* @__PURE__ */ new Map()
});
var JU_HONG_E_COMMANDS = registryState.juHongECommands;
function resolveRegistration(registration, api) {
  if (typeof registration === "function") {
    return registration(api);
  }
  return registration;
}
function createCommand(definition) {
  return {
    ...definition,
    forms: definition.forms ? definition.forms.map(clonePromptMarkdownAsset) : void 0,
    instructions: definition.instructions ? definition.instructions.map(clonePromptMarkdownAsset) : void 0,
    kind: "ju-hong-e",
    rules: definition.rules ? definition.rules.map(
      (ruleAsset) => !isPromptRuleGroupAsset(ruleAsset) ? clonePromptMarkdownAsset(ruleAsset) : {
        ...ruleAsset,
        fileNamePatterns: ruleAsset.fileNamePatterns ? [...ruleAsset.fileNamePatterns] : void 0,
        rules: ruleAsset.rules ? ruleAsset.rules.map(clonePromptMarkdownAsset) : void 0
      }
    ) : void 0
  };
}
var REGISTRATION_API = {
  createCommand
};
function addCommand(registration) {
  ensureDefaultSecurityRules();
  const definition = resolveRegistration(registration, REGISTRATION_API);
  if (JU_HONG_E_COMMANDS.has(definition.command)) {
    throw new Error(`\uC774\uBBF8 \uB4F1\uB85D\uB41C \uC8FC\uD64D\uC774 \uBA85\uB839\uC5B4\uC785\uB2C8\uB2E4. command=${definition.command}`);
  }
  JU_HONG_E_COMMANDS.set(definition.command, definition);
}

// src/command-modules/watch-pr-review-config/index.ts
addCommand(
  ({ createCommand: createCommand2 }) => createCommand2({
    command: "/watch-pr-review-config",
    description: "watch-pr-review \uAC10\uC2DC \uB300\uC0C1 \uC800\uC7A5\uC18C \uC124\uC815 \uD30C\uC77C(repos.json)\uC744 \uC5D0\uB514\uD130\uB85C \uC5F4\uAE30",
    /**
     * @description watch-pr-review 설정 파일을 에디터로 연다.
     * @param context 명령 실행 컨텍스트
     * @returns 빈 실행 결과
     */
    execute: async (context) => {
      runWatchPrReviewConfigAction({
        paths: context.paths,
        trace: context.trace
      });
      return {};
    },
    matchKeywords: ["watch", "pr", "review", "config", "settings"],
    order: 40
  })
);
