/**
 * Compliance report generators
 * Generates audit-ready reports from compliance maps
 * Absorbed from AI-Agent-Governance-Compliance-Kit/packages/compliance-engine/src/reporter.js
 */

/**
 * Generate a markdown compliance report
 * @param {Object} complianceMap - Output from mapper.mapPolicies()
 * @returns {string} Markdown report
 */
export function generateMarkdownReport(complianceMap) {
  const { framework, project, summary, controls, generated_at } = complianceMap;

  const riskLevel = getRiskLevel(summary.coverage_percentage);

  let md = `# ${framework} Compliance Report -- Agent Operations\n\n**Project:** ${project}  \n**Generated:** ${generated_at}  \n**Risk Level:** ${riskLevel}\n\n---\n\n## Executive Summary\n\n| Metric | Value |\n|---|---|\n| Framework | ${framework} |\n| Total Controls | ${summary.total_controls} |\n| Covered | ${summary.covered} |\n| Partial | ${summary.partial} |\n| Gaps | ${summary.gaps} |\n| **Coverage** | **${summary.coverage_percentage}%** |\n\n`;

  md += `### Coverage: ${generateCoverageBar(summary.coverage_percentage)}\n\n`;
  md += `---\n\n## Control Details\n\n`;

  const categories = {};
  for (const control of controls) {
    if (!categories[control.category]) {
      categories[control.category] = [];
    }
    categories[control.category].push(control);
  }

  for (const [category, categoryControls] of Object.entries(categories)) {
    md += `### ${category}\n\n`;
    for (const control of categoryControls) {
      md += generateControlSection(control);
    }
  }

  const gaps = controls.filter(c => c.status === 'gap');
  const partials = controls.filter(c => c.status === 'partial');

  if (gaps.length > 0 || partials.length > 0) {
    md += `---\n\n## Remediation Plan\n\n`;

    if (gaps.length > 0) {
      md += `### Critical Gaps (${gaps.length})\n\n`;
      for (const gap of gaps) {
        md += `**${gap.control_id} -- ${gap.title}**\n`;
        for (const rec of gap.gap_recommendations) {
          md += `- ${rec}\n`;
        }
        md += `\n`;
      }
    }

    if (partials.length > 0) {
      md += `### Partial Coverage (${partials.length})\n\n`;
      for (const partial of partials) {
        md += `**${partial.control_id} -- ${partial.title}**\n`;
        for (const rec of partial.gap_recommendations) {
          md += `- ${rec}\n`;
        }
        md += `\n`;
      }
    }
  }

  md += `---\n\n## Attestation\n\nThis report was auto-generated by DashClaw Compliance Engine.\n\n`;
  md += `**What this report proves:**\n`;
  md += `1. Agent guardrail policies have been mapped to ${framework} controls\n`;
  md += `2. Coverage gaps have been identified with specific remediation steps\n`;
  md += `3. Policy enforcement is testable and verifiable\n\n`;

  return md;
}

function generateControlSection(control) {
  const statusLabel = { covered: 'COVERED', partial: 'PARTIAL', gap: 'GAP' };

  let section = `#### ${control.control_id} -- ${control.title} [${statusLabel[control.status]}]\n\n`;
  section += `> ${control.description}\n\n`;
  section += `**Relevance to agents:** ${control.agent_relevance}\n\n`;

  if (control.matched_policies.length > 0) {
    section += `**Mapped Policies:**\n`;
    for (const mp of control.matched_policies) {
      section += `- \`${mp.policy_id}\`: ${mp.policy_description}\n`;
      section += `  - Coverage: ${mp.mapping_coverage} -- ${mp.rationale}\n`;
    }
    section += `\n`;
  }

  if (control.gap_recommendations.length > 0) {
    section += `**Recommendations:**\n`;
    for (const rec of control.gap_recommendations) {
      section += `- ${rec}\n`;
    }
    section += `\n`;
  }

  return section;
}

function getRiskLevel(coveragePercentage) {
  if (coveragePercentage >= 80) return 'LOW';
  if (coveragePercentage >= 60) return 'MEDIUM';
  if (coveragePercentage >= 40) return 'HIGH';
  return 'CRITICAL';
}

function generateCoverageBar(percentage) {
  const filled = Math.round(percentage / 5);
  const empty = 20 - filled;
  return `[${'#'.repeat(filled)}${'-'.repeat(empty)}] ${percentage}%`;
}

/**
 * Generate JSON compliance report (machine-readable)
 */
export function generateJsonReport(complianceMap) {
  return JSON.stringify(complianceMap, null, 2);
}
