Tony Romo has agreed to the largest sports analyst contract in TV history, a deal to remain at CBS which will prevent him from reaching the free-agent market, where ESPN was poised to aggressively bid for him, The Post has learned.

The contract will pay Romo around $17 million per season, which is more than the previous NFL high of $8 million per year John Madden received more than two decades ago. Even when adjusted for inflation — which would make Madden’s number $14 million — Romo still is the highest paid ever.

The deal is a long-term contract, with sources saying it is for significantly more than five years. This means the total value for Romo’s contract will surpass $100 million.

CBS was motivated this week by Disney’s ability to start bidding on Romo in March, when he could have been eligible for free agency. CBS thought that Disney — which hoped to use Romo as a carrot as it goes after a Super Bowl in the next round of negotiations — would bid $20 million per year. ESPN officials vigorously disputed that, saying they would not have even gotten close to that number.

Though Romo’s salary is astronomical for 20 NFL games, CBS officials felt he showed loyalty because he could have explored how high ESPN would go. CBS and Romo’s partner, Jim Nantz, have been universally praised since network executives Sean McManus and David Berson took the chance on putting Romo in the booth right off the field three years ago.

In Romo’s rookie deal, CBS did have a card to play that could have prevented him from becoming an unrestricted free agent.

Per the terms of Romo’s original contract, he had to tell CBS what it would take for him to agree to a contract prior to him being allowed to go on the open market, sources said. CBS was willing to meet the around $17 million per year and $100-plus milion figure that blocked out ESPN from even getting a chance.

CBS’s calculation is that they spend billions on the NFL, so bidding this high on Romo made sense in the grand scheme. They hope to retain their Sunday afternoon package and Super Bowl in the next round of negotiations with the NFL.

Romo will now earn nearly twice as much in one year than he made during his entire rookie deal, which was for three years and around $10 million. He made a little more than $3 million last season.

As for ESPN, sources have said it has alternative plans as to how it may remodel its “Monday Night Football” booth, which currently consists of Joe Tessitore and Booger McFarland.

The first call is likely to be to Peyton Manning, asking if this is finally the year he wants to try to be an analyst.

With the money Disney was planning to offer Romo and with what Romo is being paid by CBS, Manning would have to listen. If Manning says no, ESPN would have to move to Plan C. ESPN was thinking big with the Romo and the Super Bowl, but CBS had the initial foresight to sign Romo — and they refused to let him go.