On Monday morning Martin Selmayr, the secretary general of the European Commission, was in mid-flow briefing EU ambassadors on how efforts over the weekend to get legally binding assurances on the Irish backstop had ground to a halt.

Suddenly, Selmayr received a message on his phone from London.

The deal was back on.

By 8pm that evening Theresa May was on an RAF BAe 146 jet bound for Strasbourg to meet Jean-Claude Juncker.

At 10.45pm a deal was struck: May had secured three documents designed to allow the Attorney General Geoffrey Cox to change his legal advice that the backstop was "indefinite".

A cliff-hanger sequence was then in motion. Cox would endorse the Strasbourg deal 12 hours later, confirm the backstop was no longer a permanent "trap", and give the Conservative Party and DUP cover to ratify the Withdrawal Agreement.

Just over two weeks later, Brexit - the glittering prize of Theresa May’s career - would be delivered.

That was the plan.

But… just as Cordelia could inexplicably not summon up the anticipated flattery for King Lear - earning herself instant banishment and penury - the stentorian Cox himself took to the stage and, on cue, delivered the very opposite of what the script was supposed to say.

"The legal risk remains unchanged," he told an audibly deflating House of Commons the following morning. "There is no ultimate unilateral right out of this [backstop] arrangement."

Sterling plummeted. At 7.20pm the Withdrawal Agreement suffered a second thumping defeat.

What on earth went wrong?

The genesis of Tuesday’s humiliation has its roots in the Red Sea desert resort of Sharm El-Sheikh.

It was there, during the EU-Arab summit on 24-25 Februrary, that May sensed a deal on legally binding assurances on the backstop was possible.

On the margins she had met Juncker and Donald Tusk, the President of the European Council. Sources say it was during those encounters that she was able, for the first time, to crystalise what she wanted from the EU into something the EU might be able to deliver.

It revolved around a hitherto unused word in the Brexit lexicon - "capriciousness".

In a nutshell, Theresa May wanted to be sure that the UK would not be "trapped" in the backstop by the EU acting in a "capricious" manner.

"The whole point in Sharm was that May made clear she wanted assurances that would address what she claimed would be capricious behaviour by the EU," explains a senior EU diplomat.

"There would have to be some arrangement whereby if there were bad faith on the part of the EU, there would have to be some kind of relief from the backstop for the UK."

Things looked promising. Juncker was clear he could encourage the EU to accept legally binding additions to accommodate the "capriciousness" concept.

The problem was, the man Theresa May had entrusted to spearhead the UK’s mission, and on whose delphic utterances success would hinge, was on a different legal track.

Geoffrey Cox had told Mrs May on 13 November that the UK could become permanently trapped in the backstop.

So overturning that advice was key. However, not only would he be tasked with interpreting these forthcoming assurances, he would negotiate them as well.

But when he arrived in Brussels as part of the UK negotiating team the chemistry was not good.

According to a senior official, when Michel Barnier welcomed him to Brussels, Cox boomed: "I haven’t been here in forty years!"

"It was like a badge of honour," grumbled the official.

Barnier’s team also felt they’d had to walk Cox through the complexities of the backstop from scratch. "It was the fact of, at this late, late stage in the game," says one official, "having to go through the motions again, bringing him along, explaining the story."

It was not until the evening of Tuesday 5 March that Cox finally tabled formal proposals during a three-hour meeting in Brussels.

It turned out to be a very difficult encounter.

Cox infuriated Barnier’s deputy Sabine Weyand by calling her "my dear" during what were described as "robust" exchanges.

EU negotiators then realised that the bulk of his proposals were actually at odds with May’s focus at Sharm El-Sheikh on the concept of "capricousness".

May wanted a way to escape the backstop by proving the EU was acting in bad faith, i.e. capriciously. Cox, on the other hand, believed bad faith was difficult to prove.

"He had a totally different approach," says one senior figure. "Instead of focusing on preventing the EU showing bad faith, he argued that the very fact of good faith by the UK, in and of itself, justified a unilateral withdrawal by the UK from the backstop."

To bolster the good faith argument, Cox added another new word into the lexicon: reasonableness, a Victorian legal concept that, he hoped, would allow an arbitration panel to rule in the UK’s favour in a way that could sidestep’s the involvement of the European Court of Justice (ECJ).

The ECJ would - in all likelihood - have to give the last word on whether a new trade deal really did remove the need for checks on the Irish border. That would be based on a straightforward interpretation of EU and single market rules, not airy concepts of capriciousness or reasonableness.

The Attorney General was already on the defensive. The UK had had to drop the very public demands for a unilateral exit clause or expiry date. Cox therefore wanted independent arbitration to be the next best thing as a way out.

He first suggested the arbitration be outside the dispute mechanisms already enshrined in the Withdrawal Agreement. That was immediately rejected by Barnier.

He then made further arguments which baffled and irritated the EU side.

First, he suggested that if the trade negotiations broke down then it would, by default, mean the backstop applying indefinitely.

Since Article 50 was designed to be a temporary state, that meant the EU was breaking its own rules.

Cox then argued that Northern Ireland citizens would be subject to single market rules, yet not represented in the European Parliament or in ministerial meetings. The backstop was therefore in breach of the European Convention on Human Rights (ECHR).

Combine those arguments and the UK should be entitled to walk away from the backstop. EU officials were in disbelief.

"There was a fundamental disagreement," recalls one official, briefed on the dinner. "It wasn’t on the principle of arbitration. It was on what the arbitration can cover, and what comes next."

The mood in Brussels darkened. Cox and Steve Barclay, the Brexit Secretary, returned to London. Sabine Weyand continued technical talks with Olly Robbins, her opposite number.

On Thursday morning Cox addressed an angry House of Commons, which was convinced the talks were going nowhere. Cox gave little away, but cryptically pointed to the focus of the UK effort.

"The problem is," he told MPs, "that even though the arbitration system applies to the [Irish] Protocol, the question that one asks the arbitrator is at the heart of the effectiveness of any arbitration".

In other words, would Theresa May’s concept of capriciousness be the question that arbitrator was considering, or Cox’s concept of reasonableness?

Michel Barnier, meanwhile, had been due to travel to Dublin on the night of Thursday 7 March to enjoy a long-arranged family weekend, taking in the Ireland-France Six Nations clash with his two sons on Sunday.

Irish officials had set up potential meetings with the Taoiseach and Tánaiste on the Friday. However, things looked so uncertain that Barnier decided to remain in Brussels both to brief member states, and to be available in case things got back on track.

On Friday morning the EU believed the UK was already blaming Brussels for the breakdown. Theresa May gave a speech in Grimsby effectively saying it was up to the EU to move. Brussels also wanted to dampen speculation about what they were willing to offer.

"We had to explain publicly what was happening and get it out there before the weekend takes over and the UK press goes mad," says one official.

Weyand and Barnier gave a downbeat assessment to EU ambassadors in the Europa Building in Brussels, returning to the Commission at 4.30pm. At 5pm Barnier made a very public offer - on Twitter.

The EU was now offering a "legally binding interpretation of the Brexit Withdrawal Agreement".

Arbitration was the key. Both sides could agree a Joint Interpretative Statement, legally-binding, which would strengthen the UK’s ability to take action if the EU was acting in bad faith.

Because this was a legally binding interpretation, it would be more "actionable" through the arbitration process. Stefaan De Rynck, an EU Task Force spokesman, tweeted: "This is not recycling; it is an additional legal reassurance in case the EU fails to deploy best endeavours to conclude an agreement that replaces the backstop."

There was a second gambit. Mr Barnier also tweeted: "[The] EU commits to give UK the option to exit the Single Customs Territory unilaterally, while the other elements of the backstop must be maintained to avoid a hard border. UK will not be forced into customs union against its will."

Here, officials say that he was reminding London that the British side had requested a UK-wide customs backstop - the Single Customs Territory - which had then morphed into the alleged "trap" that would keep the whole of the UK bound up in the EU’s customs sphere.

In other words, if the UK hated that element of the backstop so much, they were welcome to return to the original Northern Ireland-specific backstop. "It was their situation to go into it," says an official. "If they don’t want it any more they don’t have to have it."

But that soured the mood in Westminster. "This is a retreat back to the proposal of an Northern Ireland only backstop previously rejected by all sides in the House of Commons," tweeted DUP MP Nigel Dodds.

Although the Withdrawal Agreement still contains that option, it was dropped as part of the re-packaging that was now on offer.

On Saturday morning Olly Robbins, who had gone back to London 24 hours earlier, returned to Brussels.

Barnier, meanwhile, had got the first Ryanair flight to Dublin, due to come back to Charleroi on Sunday night as scheduled, but prepared to come back first thing on Sunday morning, missing the rugby match if need be.

Despite the widespread sense that the negotiations were dead, Robbins and Sabine Weyand spent the day working on texts that had been in the mix.

Downing Street began briefing lobby correspondents that May’s jet was on standby at RAF Northolt to whisk the prime minister to Brussels at a moment’s notice.

By 8pm on Saturday night, Cox and Weyand concluded two new documents. One was the all-important legally binding additional text, entitled Instrument relating to the agreement on the withdrawal of the United Kingdom of Great Britain and Northern Ireland from the European Union.

The second was a Joint Statement by the European Commission and the UK that would supplement the non-binding Political Declaration on the future relationship.

EU officials had already cleared the Commission’s Monday morning schedule to make room for a possible May-Juncker meeting. But a meeting on Sunday night would be even better. Time was short.

But the plan had to be run through the UK Cabinet. On Sunday morning Olly Robbins was back in London briefing ministers. By noon things were looking promising. A May-Juncker meeting looked like it could go ahead on Sunday night to seal the deal.

But then, a troubling silence from London.

"There was a pause mid-afternoon," says one official.

Another official described a period of tense waiting: "There was a sense that the deal was done, the PM is on board, she’s coming with secretary of state and the attorney general. Then, it changed. She might be coming alone. Then…she might not be coming at all."

In Dublin, Michel Barnier was anxiously looking at his phone from the stand of the Aviva Stadium.

By late afternoon the message from London was: "Wait."

Finally, at 8.30pm on Sunday evening May phoned Juncker. She had failed to convince her Cabinet. The meeting was off.

There are strong indications that the stiffest - or perhaps the most influential - resistance from within the Cabinet was from the member for Torridge and West Devon, Geoffrey Cox QC.

On Monday morning EU ambassadors were once again being briefed by Michel Barnier and Martin Selmayr.

On this occasion Barnier was furious. In Dublin, before travelling to the Aviva Stadium, Barnier had read an interview Cox gave to Mail on Sunday correspondent Dan Hodges.

In answer to the question as to what Cox intended "to wrest from the cold, dead hand of Michel Barnier and Jean-Claude Juncker, to save the day for the nation," the Attorney General replied: "If we did secure an arbitration mechanism, it could be triggered on the very first day we entered the backstop. That’s because the transition period would have already given two years for completion of [trade] negotiations."

Having spent the best part of two weeks trumpeting the EU’s capacity for "bad faith", Cox’s comments appeared to Barnier to be the very thing he was accusing Brussels of.

EU officials wondered if the Mail interview had been sanctioned, or if there was now a real rift between May and Cox.

However, it was during Barnier’s and Selmayr’s otherwise gloomy briefing that the message came in from London that a deal might be back on. Juncker was travelling to Strasbourg for the European Parliament plenary session. Might May meet him there?

Key to the breakthrough was a third document: a Unilateral Declaration by the UK about the backstop.

The idea had been around for weeks. In essence, it would be an attempt to give the UK as much of a semblance of having a "unilateral" capacity over the backstop as possible.

What was involved?

London would draw up a Unilateral Declaration on the circumstances in which the backstop applied. In the declaration, the UK would try to strengthen as far as possible a legal pathway to getting out of the backstop.

Unilateral Declarations are often added to treaties to clarify their meaning. In 2009, indeed, Ireland attached a Unilateral Declaration to the Lisbon Treaty, clarifying that nothing in the treaty impinged on Ireland’s neutrality.

In this case, however, the UK would clearly not be able to unilaterally declare it could just exit the backstop on its own terms.

If that was the intention the EU would simply issue a counter-declaration, and the UK declaration would be "legally dead", in the words of one British source.

However, if the UK issued a declaration that the EU could live with, then the very fact that Brussels did not issue a counter-declaration, would give that declaration some useful legal weight in the future.

In other words, by tacitly acquiescing to the declaration, the EU was allowing it to have legal status, and the UK could then use that in a future arbitration case.

But the EU would have to be satisfied that whatever the declaration contained would not cause any problems for Ireland, or for the EU, in the future. It would be a unilateral declaration, but the EU would be holding the pen.

"The UK is a western nation," says one EU source. "It has links with other countries. It can’t just pull off a unilateral declaration unless it’s OK."

Officials on both sides then spent the next hours trying to agree a text that would have teeth, but not so far as to undermine the legal operability of the backstop. Irish officials, who had known for several weeks that some kind of unilateral declaration might be in the mix, were kept in the loop.

By mid morning Downing Street was briefing lobby correspondents that Strasbourg was on the cards. In Dublin there was a brief mention of Strasbourg, in Cabinet, getting under way a day early because of St Patrick’s Day departures.

However, matters were complicated when the Tánaiste Simon Coveney was challenged at a post-Cabinet doorstep by Sunday Times journalist Niamh Lyons over Strasbourg, and whether Ireland had conceded anything.

His affirmative response that Strasbourg was going ahead went somewhat further than the reality: at that point the meeting was not confirmed. Coveney’s intervention had the effect of actually pressurising both sides to ensure a meeting did go ahead.

But it was clear something was coming together. Leo Varadkar postponed his trip to Washington by a day. Teams of advisers gathered in both the Taoiseach’s and Tánaiste’s offices. Ireland’s Attorney General Seamus Woulfe joined in.

Contacts went back and forth to Brussels. John Callinan, the Government’s senior Brexit negotiator, spoke by phone several times to his opposite number Olly Robbins.

By late afternoon the Cabinet was recalled. The Taoiseach briefed ministers on the Unilateral Declaration draft, which was by no means concluded.

Was there nervousness on the Irish side?

British sources spoke of a "massive row" with Dublin, and "massive pushback" from Ireland. At 9.05pm, the BBC’s political editor Laura Keunnsberg tweeted: "Nerves in Dublin at Cabinet meeting tonight of third part of poss brexit tweaks - idea UK can make its own 'unilateral' statement."

However, Irish sources strongly contest the idea of "pushback" or nerves.

"There was no underestimation of the potential," says one Dublin source, "of any of these big moments to be huge, or to be used against you. There was wariness, without a doubt. But people weren’t walking around nervously."

One EU source says: "The Irish weren’t super nervous - but a unilateral declaration sounds a bit scary. It’s normal you’d be a bit nervous."

Nerves or not, the reality was that when Theresa May arrived in Strasbourg at 9.30pm local time with Brexit secretary Stephen Barclay - but without Geoffrey Cox - officials still had not concluded the text.

"Normally with these things you’ve done all the homework, and it’s just about dotting the ‘i’s and crossing the ‘t’s," says one official.

"But this wasn’t the case. The meeting was supposed to start at 8pm but she didn’t get there till 9.30pm, which suggests she was trying to convince people in London."

At 10pm May’s deputy David Lidington told the House of Commons that the prime minister had secured "legally binding changes" to the backstop, but he only mentioned two documents - the Joint Instrument and the Joint Statement - and not the Unilateral Declaration.

By all accounts, things were tense in Strasbourg. "It was absolute down to the wire stuff," says one official close to the talks. In fact, it took a final phone call between Juncker and Varadkar to get the third document - the Unilateral Declaration - over the line.

What did the text say?

In essence the Unilateral Declaration distilled some of Cox’s critique of the backstop, i.e. that it was potentially a permanent state, contrary to the legal intention of Article 50.

It also stated that the UK wished to "record its understanding" that if it was not possible for both sides to conclude a trade agreement to supersede the backstop, then this was a "breach" of the Withdrawal Agreement’s "good faith" obligations.

In such a scenario, the UK "would not consider [the backstop] to be temporary," as in its view "the Protocol would then constitute a permanent relationship between the [European] Union and the United Kingdom".

Because both sides did not intend for the Protocol to be permanent, and if it simply wasn’t possible to conclude the free trade agreement, the UK was again recording its "understanding" that there was nothing to stop it "instigating measures that could ultimately lead to disapplication of obligations under the Protocol."

In other words, the UK was declaring that the backstop was not supposed to be permanent, but if the trade talks broke down then it would become permanent. Therefore, there was nothing to stop the UK getting out through the arbitration process.

So this was the heart of the "unilateral" trigger.

However, the EU and Ireland insisted on two vital caveats.

First, the measures the UK would be able to "instigate" to exit the backstop could only be facilitated by the dispute resolution part of the Withdrawal Agreement.

In other words, Britain would still have to go through the same machinery as already provided for. And that machinery sets the bar high for either party to be able to "suspend" the application of the Protocol.

If the UK felt the EU had not been acting in "good faith" and using "best endeavours" to quickly conclude a free trade agreement, or agree "alternative arrangements" - such as technology - to be in place by the end of 2020, then it could take a case to arbitration.

But arbitration would first have to find in the UK’s favour, then impose a sanction on the EU to change its approach, then the EU would have to repeatedly ignore the sanction before Britain could trigger only a temporary suspension of the backstop.

The second caveat was the last piece of the jigsaw.

The Unilateral Declaration accepts that any suspension of the backstop could only happen "under the proviso that the UK will uphold its obligations under the 1998 [Good Friday] Agreement in all its dimensions and under all circumstances and to avoid a hard border on the island of Ireland".

In other words, even if things got to that point, the UK would have to abide by the overall objective of no hard border, and its obligations under the peace process. These, of course, are the very essence of the backstop.

British officials insisted that despite these last minute insertions, there was new and binding stuff in the overall deal.

"It’s the obvious middle way through," said one official in the early hours of Tuesday morning. "The EU can’t hold us, we don’t have a unilateral exit, so it’s the middle option."

London highlighted what Emmanuel Macron had said on 25 November, after the divorce treaty was agreed by May and the other 27 leaders.

Back then Macron had threatened that if the UK was not flexible during the trade negotiations on access to UK waters for European fishing fleets, then that would hold up those negotiations and - as a consequence - keep the UK in the backstop.

UK officials now believed that the legally binding texts secured in Strasbourg meant that such a threat would constitute bad faith, and was more actionable than before.

Immediately after the deal was struck, Theresa May told reporters that through the final text the UK was declaring that if the trade negotiations broke down irretrievably, then "there would be nothing to prevent the UK instigating measures that would ultimately dis-apply the backstop".

In reality, the "would" should have been "could". The backstop would only be "disapplied" if the panel agreed the EU was acting in bad faith.

What would Geoffrey Cox say? Would this be enough for him to reverse his legal advice that the backstop could be indefinite?

The mood around Westminster was uncertain, with rumour and gossip that he was tilting one way then the next.

Shortly after 10.30am his three-page letter to Theresa May appeared.

He acknowledged that the Joint Instrument - the assurances on the temporary nature that Barnier had offered the previous Friday - was legally binding. It converted the 14 January letter from Donald Tusk and Jean-Claude Juncker into legal form and with "useful clarifications, amplifications of existing obligations and some new obligations," which would allow the UK to take a case if the EU breached its "good faith" and "best endeavours" obligations.

If the EU "systematically" refused to consider "alternative arrangements" to the backstop that it didn’t like, then that could be seen as a breach. Both sides were now committed to finding those alternatives by the end of 2020, and if not efforts were to be "redoubled".

The Joint Instrument also committed both sides to a separate negotiating track, the moment the treaty was ratified, to find ways of replacing the regulatory alignment elements of the backstop with "comprehensive customs cooperation arrangements, facilitative arrangements and technologies".

These, Cox wrote, were "materially new legal obligations and commitments".

He added it would be "unconscionable and a potential breach of the duties of good faith and best endeavours were the EU to decline to adopt any practicable alternative arrangements".

The EU would simply have to show "a pattern of unjustified delay," for the UK to claim at arbitration that the EU had breached the good faith obligations.

As for the unilateral declaration, he wrote, this constituted an "authentic interpretation" of the Withdrawal Agreement "if it is accepted by the other party".

Even though it was not an "agreed" document, it still had legal status.

Overall, therefore, both the Joint Instrument and the Unilateral Declaration provided a "substantive and binding reinforcement" of the UK’s rights.

For Theresa May, so far so good.

While Cox had said last November that the backstop could apply permanently if the trade talks broke down, that risk was now reduced - at least insofar as it was possible to show the EU had acted in bad faith.

Ultimately, given all the above, both sides should be able to find a replacement for the backstop.

However…(and this was the killer blow), that was a political judgement.

"The legal risk remains unchanged."

If it was the case that both sides simply could not conclude a trade deal that replaced the backstop - not because of bad faith, but simply because of intractable differences - then the UK had "no internationally lawful means" of exiting backstop unilaterally.

The scepticism expressed by the DUP and European Research Group overnight was now confirmed. For the second time, the Withdrawal Agreement was doomed.

In Brussels there was disbelief. "The whole drama was to get Cox on board," said a senior EU official. "That’s why it took so long. How could she commit to a text if she was not sure she had the AG on board?"

As an epilogue to the Strasbourg drama, Geoffrey Cox returned to the fray after the Withdrawal Agreement was defeated by 149 votes on Tuesday, and Westminster voted to delay Article 50 on Thursday, pending one final throw of the dice next week for the treaty.

With the DUP now keen for a ladder to climb down, having declared unequivocally that the Cox advice proved Theresa May had failed to get the backstop changes they demanded, the Attorney General was reported to be looking at Article 62 of the Vienna Convention in a desperate bid to give the party some cover.

Article 62 allows a country to walk away from a treaty if there has been a "fundamental change" in circumstance that were unforeseen when the treaty was agreed.

According to the Daily Telegraph, Cox was arguing that if the backstop was "having a socially destabilising effect on Northern Ireland" then that could be seen as a "fundamental change".

One legal expert in Brussels wryly pointed out that if, according to the Vienna Convention the "fundamental change" had to be "unforeseen", then you couldn’t really advertise in advance that that was your course of action.

In another week of brain-stretching chaos in London, this, perhaps, summed it all up.