#!/usr/bin/env python3
from pathlib import Path
import re

APP = Path("/opt/ligbox-wizard/frontend/src/App.jsx")
text = APP.read_text(encoding="utf-8")

pattern = r"  async function choosePortalDns\(\) \{.*?\n  \}\n\n  async function chooseByoDns"
replacement = r'''  async function choosePortalDns() {
    setDnsChoice('portal')
    setError(null)
    startBusy('dns_zone')
    try {
      const resolved = dnsResolve || (await api(`/onboarding/dns/resolve/${domain}`))
      setDnsResolve(resolved)
      const guide = await api('/onboarding/dns/cloudflare/provision-zone', {
        method: 'POST',
        body: JSON.stringify({ domain }),
      })
      setPortalGuide(guide)
      const cf = guide.status || (await refreshCfStatus())
      setCfStatus(cf)
      markActionDone('choosePortalDns')
      if (guide.verification) {
        setVerification(guide.verification)
        setResult({ type: 'dns', data: { verification: guide.verification } })
        markActionDone('verifyZone')
        markActionDone('applyPortalDns')
      } else if (cf?.zone_in_account && cf?.can_apply_mail_records) {
        markActionDone('verifyZone')
        const data = await api('/onboarding/dns/cloudflare/apply', {
          method: 'POST',
          body: JSON.stringify({
            domain,
            zone_id: guide.zone_id || resolved.zone_id,
            mail_aliases: sanitizeMailAliases(mailAliasInputs, domain),
          }),
        })
        setVerification(data.verification)
        setResult({ type: 'dns', data })
        markActionDone('applyPortalDns')
      }
    } catch (e) {
      setError(e.message)
      setDnsChoice(null)
      setActionsDone((prev) => ({ ...prev, choosePortalDns: false }))
    } finally {
      stopBusy()
    }
  }

  async function chooseByoDns'''

new_text, n = re.subn(pattern, replacement, text, count=1, flags=re.DOTALL)
if n != 1:
    raise SystemExit(f"replace failed: {n}")
APP.write_text(new_text, encoding="utf-8")
print("choosePortalDns fixed")
