from pathlib import Path

ROOT = Path.cwd()
entity = ROOT / 'src/modules/customers/entities/customer.entity.ts'
dto = ROOT / 'src/modules/customers/dto/create-customer.dto.ts'
service = ROOT / 'src/modules/customers/customers.service.ts'

# Entity columns
s = entity.read_text()
if 'loyaltyPoints' not in s:
    marker = """  @Column({ default: false })\n  isVip: boolean;\n"""
    insert = marker + """
  @Column({ type: 'int', default: 0 })
  loyaltyPoints: number;

  @Column({ nullable: true })
  loyaltyTier?: string;

  @Column('decimal', { precision: 5, scale: 2, default: 0 })
  vipDiscountPercent: number;

  @Column({ type: 'date', nullable: true })
  vipSince?: string;

  @Column('text', { nullable: true })
  vipBenefits?: string;

  @Column('text', { nullable: true })
  loyaltyHistory?: string;
"""
    s = s.replace(marker, insert)
    entity.write_text(s)

# DTO fields
s = dto.read_text()
if 'loyaltyPoints' not in s:
    marker = """  @IsOptional()\n  @IsBoolean()\n  isVip?: boolean;\n"""
    insert = marker + """
  @IsOptional()
  @IsNumber()
  loyaltyPoints?: number;

  @IsOptional()
  @IsString()
  loyaltyTier?: string;

  @IsOptional()
  @IsNumber()
  vipDiscountPercent?: number;

  @IsOptional()
  @IsString()
  vipSince?: string;

  @IsOptional()
  @IsString()
  vipBenefits?: string;

  @IsOptional()
  @IsString()
  loyaltyHistory?: string;
"""
    s = s.replace(marker, insert)
    dto.write_text(s)

# Service create/update assignments
s = service.read_text()
if 'loyaltyPoints: data.loyaltyPoints' not in s:
    s = s.replace(
"""      isVip: data.isVip ?? false,\n      isBlacklisted: data.isBlacklisted ?? false,""",
"""      isVip: data.isVip ?? false,
      loyaltyPoints: Number(data.loyaltyPoints ?? 0),
      loyaltyTier: data.loyaltyTier ?? (data.isVip ? 'gold' : 'standard'),
      vipDiscountPercent: Number(data.vipDiscountPercent ?? 0),
      vipSince: data.vipSince,
      vipBenefits: data.vipBenefits,
      loyaltyHistory: data.loyaltyHistory,
      isBlacklisted: data.isBlacklisted ?? false,"""
)
if 'loyaltyPoints: data.loyaltyPoints ?? customer.loyaltyPoints' not in s:
    s = s.replace(
"""      isVip: data.isVip ?? customer.isVip,\n      isBlacklisted: data.isBlacklisted ?? customer.isBlacklisted,""",
"""      isVip: data.isVip ?? customer.isVip,
      loyaltyPoints: data.loyaltyPoints ?? customer.loyaltyPoints,
      loyaltyTier: data.loyaltyTier ?? customer.loyaltyTier,
      vipDiscountPercent: data.vipDiscountPercent ?? customer.vipDiscountPercent,
      vipSince: data.vipSince ?? customer.vipSince,
      vipBenefits: data.vipBenefits ?? customer.vipBenefits,
      loyaltyHistory: data.loyaltyHistory ?? customer.loyaltyHistory,
      isBlacklisted: data.isBlacklisted ?? customer.isBlacklisted,"""
)
service.write_text(s)
print('Customer loyalty/VIP backend patch applied.')
