import { Router } from 'express';
import { ReputationZKPService } from '../../core/ai/ReputationZKPService';
import { BehavioralRiskService } from '../../core/governance/BehavioralRiskService';
import { requirePermission } from '../../core/guards/rbac.guard';
import { requireTraceContext } from '../../core/guards/trace-context.guard';
import { DIDHandshakeService } from '../../core/security/DIDHandshakeService';
import { PrivateAuditService } from '../../core/security/PrivateAuditService';
import { SovereigntyGovernanceService } from '../../services/SovereigntyGovernanceService';
import { SovereigntyIdentityService } from '../../services/SovereigntyIdentityService';

const router = Router();

/**
 * [BIZ_SOV_01] 主权身份管理 (Sovereignty Identity)
 */
router.post('/identity/register', requireTraceContext, requirePermission('tenant:admin'), async (req, res) => {
  try {
    const { tenantId, traceId } = (req as any).traceContext;
    const { identityData } = req.body;
    const did = await SovereigntyIdentityService.registerIdentity(tenantId, identityData, traceId);
    res.json({ success: true, data: { did } });
  } catch (err: any) {
    res.status(500).json({ success: false, error: err.message });
  }
});

router.get('/identity/status', requireTraceContext, requirePermission('tenant:read'), async (req, res) => {
  try {
    const { tenantId } = (req as any).traceContext;
    const identity = await SovereigntyIdentityService.getIdentity(tenantId);
    res.json({ success: true, data: identity });
  } catch (err: any) {
    res.status(500).json({ success: false, error: err.message });
  }
});

/**
 * [CORE_SEC_16] 基于 DID 的跨租户安全握手 (DID Handshake)
 */
router.post('/handshake/initiate', requireTraceContext, requirePermission('tenant:admin'), async (req, res) => {
  try {
    const { tenantId } = (req as any).traceContext;
    const { targetTenantId, sourceDid, targetDid } = req.body;
    const sessionId = await DIDHandshakeService.initiateHandshake({
      sourceTenantId: tenantId,
      targetTenantId,
      sourceDid,
      targetDid
    });
    res.json({ success: true, data: { sessionId } });
  } catch (err: any) {
    res.status(500).json({ success: false, error: err.message });
  }
});

router.post('/handshake/verify', requireTraceContext, requirePermission('tenant:admin'), async (req, res) => {
  try {
    const { sessionId, proof } = req.body;
    const isValid = await DIDHandshakeService.verifyHandshake(sessionId, proof);
    res.json({ success: true, data: { isValid } });
  } catch (err: any) {
    res.status(500).json({ success: false, error: err.message });
  }
});

/**
 * [BIZ_SOV_04] 主权治理与决策审计 (Sovereign Governance)
 */
router.post('/governance/propose', requireTraceContext, requirePermission('tenant:admin'), async (req, res) => {
  try {
    const { tenantId, traceId } = (req as any).traceContext;
    const { proposalType, data } = req.body;
    const proposalId = await SovereigntyGovernanceService.createProposal(tenantId, proposalType, data, traceId);
    res.json({ success: true, data: { proposalId } });
  } catch (err: any) {
    res.status(500).json({ success: false, error: err.message });
  }
});

/**
 * [CORE_SEC_20] 基于零知识证明的隐私审计 (Private Audit)
 */
router.post('/audit/proof/generate', requireTraceContext, requirePermission('audit:write'), async (req, res) => {
  try {
    const { tenantId } = (req as any).traceContext;
    const { auditType, sensitiveData, threshold } = req.body;
    const record = await PrivateAuditService.generateAuditProof({
      tenantId,
      auditType,
      sensitiveData,
      threshold: threshold || 0.15
    });
    res.json({ success: true, data: record });
  } catch (err: any) {
    res.status(500).json({ success: false, error: err.message });
  }
});

router.post('/audit/proof/verify', requireTraceContext, requirePermission('audit:admin'), async (req, res) => {
  try {
    const { verificationHash, auditorId } = req.body;
    const isValid = await PrivateAuditService.verifyProof(verificationHash, auditorId);
    res.json({ success: true, data: { isValid } });
  } catch (err: any) {
    res.status(500).json({ success: false, error: err.message });
  }
});

/**
 * [SOV_NET_07] 基于 ZKP 的隐私声誉分值证明 (ZKP Reputation)
 */
router.post('/reputation/verify', requireTraceContext, requirePermission('tenant:admin'), async (req, res) => {
  try {
    const { verificationHash, publicSignals } = req.body;
    const isValid = await ReputationZKPService.verifyReputationProof(verificationHash, publicSignals || {});
    res.json({ success: true, data: { isValid } });
  } catch (err: any) {
    res.status(500).json({ success: false, error: err.message });
  }
});

/**
 * [BIZ_GOV_09] 租户行为风险画像 (Behavioral Risk)
 */
router.get('/risk/status', requireTraceContext, requirePermission('audit:read'), async (req, res) => {
  try {
    const { tenantId } = (req as any).traceContext;
    const status = await BehavioralRiskService.getRiskStatus(tenantId);
    res.json({ success: true, data: status });
  } catch (err: any) {
    res.status(500).json({ success: false, error: err.message });
  }
});

export default router;