import { z } from "zod";

export const WorkflowRequirementStatusSchema = z.enum(["pending", "completed", "na"]);

export const WorkflowRequirementEvidenceStateSchema = z.object({
  id: z.string().min(1).max(220),
  documentId: z.string().min(1).max(220),
  fileName: z.string().min(1).max(500),
  uploadedAtIso: z.string().datetime({ offset: true }),
});

export const WorkflowRequirementStateSchema = z.object({
  id: z.string().min(1).max(220),
  title: z.string().min(1).max(500),
  description: z.string().min(1).max(2500),
  category: z.enum(["administrativo", "legal", "tecnico", "economico", "general"]),
  mandatory: z.boolean(),
  source: z.enum(["official_format", "required_checklist", "critical_requirement", "lock_in"]),
  status: WorkflowRequirementStatusSchema,
  note: z.string().max(1200),
  evidences: z.array(WorkflowRequirementEvidenceStateSchema).max(50).default([]),
});

export const WorkflowMilestoneSourceSchema = z.enum(["ai", "licitation", "manual"]);

export const WorkflowTechnicalSectionStateSchema = z.object({
  id: z.string().min(1).max(220),
  title: z.string().min(1).max(500),
  description: z.string().min(1).max(2500),
  completed: z.boolean(),
});

export const WorkflowEconomicItemStateSchema = z.object({
  id: z.string().min(1).max(220),
  concept: z.string().max(500),
  unit: z.string().max(120),
  quantity: z.number().finite().min(0).max(1_000_000),
  unitPrice: z.number().finite().min(0).max(1_000_000_000),
});

export const WorkflowMilestoneStateSchema = z.object({
  id: z.string().min(1).max(220),
  title: z.string().min(1).max(500),
  dateIso: z.string().datetime({ offset: true }).nullable(),
  location: z.string().max(800),
  note: z.string().max(1200),
  source: WorkflowMilestoneSourceSchema.default("manual"),
});

export const WorkflowSignatureComplianceStateSchema = z.object({
  policyStatus: z.enum(["permitido", "condicionado", "requiere_validacion_legal"]).default("requiere_validacion_legal"),
  policyName: z.string().max(320).default("Sin politica definida"),
  jurisdictionLabel: z.string().max(220).default("Jurisdiccion no definida"),
  sourceUrl: z.string().max(2000).default(""),
  minimumEvidence: z.array(z.string().max(400)).max(20).default([]),
  notes: z.string().max(1600).default(""),
  validatedByLegal: z.boolean().default(false),
});

export const ProposalWorkflowStateSchema = z.object({
  step: z.number().int().min(1).max(6),
  info: z.object({
    title: z.string().max(500),
    issuingEntity: z.string().max(500),
    procedureType: z.string().max(200),
    jurisdiction: z.string().max(200),
    state: z.string().max(200),
    municipality: z.string().max(200),
    sector: z.string().max(200),
    description: z.string().max(5000),
    convocatoriaUrl: z.string().max(2000),
  }),
  requirements: z.array(WorkflowRequirementStateSchema).max(500),
  technicalSections: z.array(WorkflowTechnicalSectionStateSchema).max(200),
  economicItems: z.array(WorkflowEconomicItemStateSchema).max(2000),
  milestones: z.array(WorkflowMilestoneStateSchema).max(500),
  signatureCompliance: WorkflowSignatureComplianceStateSchema.default({
    policyStatus: "requiere_validacion_legal",
    policyName: "Sin politica definida",
    jurisdictionLabel: "Jurisdiccion no definida",
    sourceUrl: "",
    minimumEvidence: [],
    notes: "",
    validatedByLegal: false,
  }),
  readyMarked: z.boolean(),
});

export type ProposalWorkflowState = z.infer<typeof ProposalWorkflowStateSchema>;
export type WorkflowRequirementState = z.infer<typeof WorkflowRequirementStateSchema>;

export type ProposalWorkflowGate = {
  mandatoryCount: number;
  resolvedCount: number;
  docsReady: boolean;
  technicalReady: boolean;
  economicReady: boolean;
  datesReady: boolean;
  signatureReady: boolean;
  infoReady: boolean;
  allReady: boolean;
};

export function clampWorkflowStep(value: number) {
  return Math.max(1, Math.min(6, Math.round(value)));
}

export function computeWorkflowGate(workflow: ProposalWorkflowState): ProposalWorkflowGate {
  const mandatoryRequirements = workflow.requirements.filter((item) => item.mandatory);
  const resolvedRequirements = mandatoryRequirements.filter((item) => item.status !== "pending" && (item.status === "na" || item.evidences.length > 0)).length;
  const docsReady = mandatoryRequirements.length > 0 && resolvedRequirements === mandatoryRequirements.length;

  const technicalReady = workflow.technicalSections.length > 0 && workflow.technicalSections.every((item) => item.completed);
  const economicReady =
    workflow.economicItems.length > 0 &&
    workflow.economicItems.every((item) => item.concept.trim().length > 0 && item.quantity > 0 && item.unitPrice >= 0);
  const datesReady = workflow.milestones.length > 0 && workflow.milestones.every((item) => Boolean(item.dateIso));
  const signatureReady =
    workflow.signatureCompliance.policyStatus !== "requiere_validacion_legal" || workflow.signatureCompliance.validatedByLegal;
  const infoReady = workflow.info.title.trim().length > 0 && workflow.info.issuingEntity.trim().length > 0;

  return {
    mandatoryCount: mandatoryRequirements.length,
    resolvedCount: resolvedRequirements,
    docsReady,
    technicalReady,
    economicReady,
    datesReady,
    signatureReady,
    infoReady,
    allReady: docsReady && technicalReady && economicReady && datesReady && signatureReady && infoReady,
  };
}

export function computeWorkflowCompletionPercent(workflow: ProposalWorkflowState) {
  const gate = computeWorkflowGate(workflow);
  const stepCompletion = [gate.infoReady, gate.docsReady, gate.technicalReady, gate.economicReady, gate.allReady, gate.datesReady];
  return Math.round((stepCompletion.filter(Boolean).length / 6) * 100);
}
