import * as NodeServices from '@effect/platform-node/NodeServices';
import * as NodeCrypto from '@effect/platform-node/NodeCrypto';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import * as Schema from 'effect/Schema';
import { execFileSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
import { writeFileSync } from 'node:fs';

// A runtime command using the checkout's production services and real Git subprocesses.
// There are no mocked CLIs, transports, repositories, or service results.
const [appDir, cwd, reportPath] = process.argv.slice(2);
const moduleAt = (p: string) => import(pathToFileURL(`${appDir}/${p}`).href);
const Git = await moduleAt('apps/server/src/vcs/GitVcsDriver.ts');
const Identity = await moduleAt('apps/server/src/project/RepositoryIdentityResolver.ts');
const Config = await moduleAt('apps/server/src/config.ts');
const Contracts = await moduleAt('packages/contracts/src/index.ts');
const git = (...args: string[]) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore','pipe','pipe'] }).replace(/\r?\n$/, '');
const visible = (s: string) => s.replaceAll('\u00a0', '<U+00A0>');
const baseLayers = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer);
const config = Config.layerTest(cwd, `${cwd}/runtime-home`).pipe(Layer.provide(baseLayers));
const layers = Layer.mergeAll(Git.layer.pipe(Layer.provide(config)), Identity.layer).pipe(Layer.provide(baseLayers));
const result = await Effect.runPromise(Effect.gen(function*() {
  const driver = yield* Git.GitVcsDriver;
  const resolver = yield* Identity.RepositoryIdentityResolver;
  const report: string[] = [];
  const identities: string[] = [];
  const locatorNames: (string | null)[] = [];
  for (const variant of ['direct', 'rewritten']) {
    for (const name of git('remote').split('\n').filter(Boolean)) git('remote', 'remove', name);
    git('remote', 'add', '\u00a0', 'https://github.com/octocat/Hello-World.git');
    if (variant === 'rewritten') git('config', 'url.https://mirror.example.invalid/.insteadOf', 'https://github.com/');
    const fetchLine = git('remote', '-v').split('\n').find((line: string) => line.includes('(fetch)')) ?? '';
    report.push(`GIT ${variant} fetch: ${visible(fetchLine.split('\t')[1] ?? fetchLine)}`);
    const identity = yield* resolver.resolve(cwd, { refresh: true });
    let wire = identity === null ? null : yield* Schema.encodeEffect(Contracts.RepositoryIdentity)(identity);
    identities.push(identity?.canonicalKey ?? 'null');
    locatorNames.push(wire?.locator.remoteName ?? null);
    report.push(`IDENTITY ${variant}: ${identity?.canonicalKey ?? 'null'}`);
    report.push(`  exact locator: ${visible(JSON.stringify(wire?.locator.remoteName ?? null))}`);
    if (variant === 'rewritten') git('config', '--unset', 'url.https://mirror.example.invalid/.insteadOf');
  }
  // A genuine local bare repository receives the push; no forge or provider is impersonated.
  for (const name of git('remote').split('\n').filter(Boolean)) git('remote', 'remove', name);
  git('init', '--bare', '--quiet', `${cwd}/destination.git`);
  git('remote', 'add', '\u00a0', `${cwd}/destination.git`);
  const status = yield* driver.statusDetailsLocal(cwd);
  report.push(`STATUS only remote is U+00A0: hasOriginRemote=${status.hasOriginRemote}`);
  git('remote', 'rename', '\u00a0', 'publish\u00a0');
  const pushed = yield* driver.pushCurrentBranch(cwd, null, { remoteName: 'publish\u00a0' }).pipe(
    Effect.map((value) => ({ ok: true, value })),
    Effect.catch((error: { detail?: string }) => Effect.succeed({ ok: false, error: (error.detail ?? '').split('\n')[0] })),
  );
  const localHead = git('rev-parse', 'HEAD');
  let destinationHead = '';
  try { destinationHead = git('--git-dir', `${cwd}/destination.git`, 'rev-parse', 'refs/heads/main'); } catch {}
  report.push(`PUBLISH explicit destination publish<U+00A0>: ${pushed.ok ? 'pushed' : 'FAILED'}`);
  if (!pushed.ok) report.push(`  Git diagnostic: ${visible(pushed.error)}`);
  report.push(`  destination main equals source HEAD: ${destinationHead === localHead}`);
  if (pushed.ok) report.push(`  upstream: ${visible(git('config', 'branch.main.remote'))}`);
  return { identities, locatorNames, hasRemote: status.hasOriginRemote, pushed: pushed.ok, received: destinationHead === localHead, report };
}).pipe(Effect.provide(layers), Effect.scoped));
writeFileSync(reportPath, result.report.join('\n') + '\n');
console.log(JSON.stringify(result));
