import { readFileSync, existsSync } from 'fs';
import { resolve } from 'path';
import { createHash } from 'crypto';
import { id as keccakId } from 'ethers';

function projectRoot(): string {
  return (
    process.env.PROXMOX_ROOT?.trim() ||
    process.env.PHOENIX_REPO_ROOT?.trim() ||
    resolve(__dirname, '../../../../../..')
  );
}

function readJson<T>(rel: string): T | null {
  const p = resolve(projectRoot(), rel);
  if (!existsSync(p)) return null;
  return JSON.parse(readFileSync(p, 'utf8')) as T;
}

/** Matches Solidity `keccak256(bytes(string))` for short jurisdiction / matrix ids. */
export function jurisdictionIdBytes32(id: string): string {
  return keccakId(id);
}

export function matrixControlIdBytes32(rowId: string): string {
  return keccakId(rowId);
}

export interface Web3ComplianceSummary {
  generatedAt: string;
  deployed: Record<string, string | null>;
  universalControls: unknown[];
  jurisdictions: Record<string, unknown>;
  gnosisSafeRecommendation: unknown;
  notarizationRequiredForRows: string[];
}

export function getWeb3ComplianceSummary(): Web3ComplianceSummary {
  const web3 = readJson<{
    universalControls: unknown[];
    jurisdictions: Record<string, { matrixRowsRequiringNotarization?: string[] }>;
    gnosisSafeRecommendation: unknown;
  }>('config/compliance/jurisdiction-web3-controls.v1.json');

  const deployed = readJson<{ contracts?: Record<string, string> }>(
    'config/compliance/web3-multisig-deployed.v1.json'
  );

  const envDeployed = {
    OMNLJurisdictionPolicyRegistry: process.env.OMNL_JURISDICTION_REGISTRY || null,
    OMNLNotaryRegistry: process.env.OMNL_NOTARY_REGISTRY || null,
    OMNLComplianceMultisig: process.env.OMNL_COMPLIANCE_MULTISIG || null,
    ReserveCommitmentStore: process.env.OMNL_RESERVE_COMMITMENT_STORE || null,
    GovernanceController: process.env.OMNL_GOVERNANCE_CONTROLLER || null,
    GnosisSafeAdmin: process.env.OMNL_GNOSIS_SAFE_ADMIN || null,
  };

  const idRows = web3?.jurisdictions?.ID?.matrixRowsRequiringNotarization ?? [];

  return {
    generatedAt: new Date().toISOString(),
    deployed: {
      ...envDeployed,
      ...(deployed?.contracts ?? {}),
    },
    universalControls: web3?.universalControls ?? [],
    jurisdictions: web3?.jurisdictions ?? {},
    gnosisSafeRecommendation: web3?.gnosisSafeRecommendation ?? null,
    notarizationRequiredForRows: idRows,
  };
}

export function buildNotarizationIntent(input: {
  jurisdictionId: string;
  matrixControlId: string;
  contentHash: string;
  merkleRoot?: string;
  metadataHash?: string;
}): Record<string, unknown> {
  const content = input.contentHash.startsWith('0x') ? input.contentHash : `0x${input.contentHash}`;
  return {
    jurisdictionId: jurisdictionIdBytes32(input.jurisdictionId),
    matrixControlId: matrixControlIdBytes32(input.matrixControlId),
    contentHash: content,
    merkleRoot: input.merkleRoot ?? `0x${'0'.repeat(64)}`,
    metadataHash: input.metadataHash ?? `0x${'0'.repeat(64)}`,
    kind: 'EvidencePackage',
    contract: process.env.OMNL_NOTARY_REGISTRY || null,
    policyConfigHash: existsSync(resolve(projectRoot(), 'config/compliance/jurisdiction-web3-controls.v1.json'))
      ? `0x${createHash('sha256')
          .update(readFileSync(resolve(projectRoot(), 'config/compliance/jurisdiction-web3-controls.v1.json')))
          .digest('hex')}`
      : null,
  };
}
