In Europe, what was once unthinkable - backing another, potentially bloody conflagration against an Islamic power while the world is still bogged down in Iraq - has become a possibility. Even before Bush started talking in October in Old Testament terms about a third world war being triggered by Iran, the French foreign minister had argued back in September that Iran's nuclear programme was bringing the west to the brink: "We have to prepare for the worst, and the worst is war."

Ahmadinejad, however, has suckered the west into a confrontation for his own reasons. He has derailed Iran's economy, squandering record oil profits and paralysing the banks. He has alienated his core support among the poor. He has brazenly attempted to rig clerical institutions, the machinery that turns out Shiadom's future leaders, so as to consolidate his rule. Such an audacious plan, from a man who could once do no wrong, has triggered a momentous fight-back from affronted clerics and senior political figures.

Those who know him best say Ahmadinejad has come to realise that it will take something momentous for him to hold on to power come the parliamentary elections next March - hence his provocations. Vali Nasr, an Iranian-born professor of international politics at Tufts University in Boston, goes so far as to say, "He desperately needs war with America to survive politically in a country that is as exhausted as Europe and the US is with his increasingly volatile grandstanding."

For a visitor, the sheer size of Iran's capital is daunting. Tehran is one of the modern megalopolises, twice as populous as London. The wealthy northern suburb of Elahieh is often highlighted as proof of the emerging new Iranian society: photographs of Gucci-clad women and men in jeans are beamed around the world as evidence of change. However, it soon becomes obvious that its influence is small. More than 10 million poor, religiously conservative residents dominate the city. They migrated here during the years of the Shah, when bungled land reforms allocated such small parcels of agricultural land to them that no one could produce enough food to survive. Today they live cheek by jowl: the chadoris, women swathed head to foot in semi-circular black robes, and the basijis, men and boys who dress like their president and who have been recruited by the million to the Basij volunteer military force of the Revolutionary Guards. They are the country's plain-clothed ears and eyes, as well as the morality police, enforcing a rigid vision of a Shia state. In the city warehouses are filled with workers trimming silk carpets destined for western showrooms they will never visit. Most have never held a passport and have little interest in seeing the world.

Ahmadinejad had barely travelled, too. He talked proudly when he stood for the presidency in 2005 of having left Iran only once, "for a short trip to Austria." He appeared to be one of the people. In Iran what you wear is a political statement, and he sounded and dressed as they did. Conjuring the time when he was among the disenfranchised mass who signed up to the Iranian Revolutionary Guards Corps established by Ayatollah Khomeini, he promised to take people back to the pious values of 1979. A turning point in his campaign came when he released a short film showing him dining cross-legged on the floor of his simple, working-class home on Tehran's 72nd square, his wife hidden by her chador. Compare this with the image of his opponent, Hashemi Rafsanjani, two-time president, a wealthy ayatollah whose family owned hundreds of acres of pistachio orchards in Kerman province, and who produced ill-judged campaign ads showing him discussing the lack of entertainment options with a group of affluent, western-dressed teenagers from Elahieh.

When Ahmadinejad appeared on the international stage he seemed unconventional, even shabby, among the crowd of sombre suits; his uniform was a crumpled jacket, buttoned-up shirt and beard, his nervous smile made him seem modest and simultaneously embarrassed. World leaders overlooked his apparent ignorance of the niceties of international diplomacy and his street vernacular, drawn from the working-class suburb of Tehran where he grew up, the youngest son of a migrant worker.

But it soon became clear that this former student of traffic management and one-time mayor of Tehran was advancing a radical conservative agenda. An intensely religious man, he began to sound Talibanesque in his pronouncements. There were no homosexuals in Iran, he said (without explaining this was because they were forced to undergo sex-change operations at the government's expense). Women belonged in the chador, he declared, as his administration published figures showing that in just two months 160,000 had been charged with being insufficiently veiled earlier this year. Public hangings - which had not been seen in the capital for many years - returned to the city's streets and were broadcast on live TV. After drawing international condemnation for restarting Iran's stalled nuclear programme, Ahmadinejad raised the temperature by sacking Ali Larijani, Iran's vastly experienced secular nuclear negotiator, replacing him with a former militia leader.

Throughout Tehran, there are 60ft-high posters depicting Iran's "martyrs", the million soldiers who fell during the eight-year war with Iraq in the 80s. The ghosts of the dead fill the city. Ahmadinejad has invoked them at every stage of his political career. He reminds people that when he was mayor in 2003, he had martyrs' bodies exhumed from their provincial cemeteries and reburied in the capital's squares so that wherever people walked there were memories of loss beneath their feet.

Patriotism was only one string he pulled. At the heart of his election message was a claim that chimed with the deeply religious poor: a divine force protected him and would help the Iranian people get closer to God, too. In a series of national roadshows that became his political signature, he insisted that messengers from heaven had told him that the Mahdi, a messiah-like figure who Iranian Shi'ites believe vanished in AD873, was about to return to the mortal world bringing salvation.

According to the sacred texts of Shi'ism, the Mahdi's reappearance would establish a just Islamic society at a time of war and chaos and, citing one such text, Ahmadinejad and his spiritual advisers declared that that time was now.

It must surely rank as one of the most hyperbolic manifesto pledges ever made, but still, it got Ahmadinejad elected. The new president then shared his vision with the UN general assembly in September 2005. During his address he appealed to God to "hasten the emergence of... the Promised One..." After he left the meeting, Ahmadinejad had a conversation with an Iranian cleric, describing how he had felt the hand of God in the UN, which was recorded and uploaded on to the net: "I felt it myself... for 27 to 28 minutes all the leaders did not blink. They were astonished... It's not an exaggeration, I was looking."

But there was no point making such grand pledges if he could not provide the evidence. Ahmadinejad began furiously investing millions of pounds to animate his claim that the Mahdi was coming. And he chose to do it at one of the holiest places in Iran.

The city of Qom, 90 miles south of Tehran, on the edge of the Kavir desert, is the scene of frenzied building work. According to local tradition, the Mahdi once appeared here in a vision to a shepherd watering his sheep at a well on the outskirts of the city, and devotees believe that it will be from this well that he re-emerges.

For several hundred years a small mosque, known as Jamkaran, stood on the vision site, attracting pilgrims who scribbled their innermost desires on scraps of paper that they threw into the well. One of Ahmadinejad's first acts in power was to have his entire cabinet sign a piece of paper that was also put down the well, a pledge to transform the mosque into a place worthy of the Mahdi's presence. Soon after, posters started appearing on the streets of Tehran declaring, "He's Coming." There was talk of a fast train link to connect Jamkaran to the capital in case the Mahdi turned up without warning, enabling politicians to get to the mosque in double-quick time.

Today it resembles an Islamic Lourdes. The modest mosque has been embellished with 100ft minarets, blue-tiled domes and new prayer halls. Hundreds of thousands of devout, working-class Iranians flock to the site, especially on Tuesday nights, the reputed time for the Mahdi's reappearance. Ahmadinejad shuttles here almost weekly, and whenever he appears he is mobbed like a rock star. A holy of holies in an ultra-conservative country, it is out of bounds to western tourists who catch only a blur of blue tiles from their coaches as they are escorted down the motorway to the archaeological sites of Esfahan, Persepolis and Shiraz.

As the sun burns red, dozens of cranes and earthmovers move along the horizon. Every road leading to the mosque is filled with chadoris, who run, clutching bags and children, to claim a small patch on the tarmac perimeter where they will eat, sleep and pray through the night. Ahead, the mosque is illuminated by a hundred thousand bulbs. Tears wash down the faces of worshippers as they catch their first glimpse of the minarets. As the muezzin's call wells up from deep inside the complex at 7pm, the crowds kneel as one in prayer.

The maddah, or storyteller, takes the crowd on an emotional late-night journey. "Come on, come on! I have a fear of not seeing You!" he cries, appealing to the Mahdi, as the crowds sway and sob. He tells stories of martyrs who have come back in his dreams to warn that Iran has lost its way, and that until it returns to its revolutionary roots they will not reach paradise. Only Ahmadinejad can be trusted to carry out this exorcism, he warns. It is a message that resounds with every family here, as all have lost brothers, sons and fathers. "We must follow our president who is brave and facing western aggression," says Farida Milani, from Yazd, who is here with her wheelchair-bound mother.

Before Ahmadinejad came along, Qom was home to one vitally important shrine, and it was not Jamkaran. The city was world-famous among Shias as the burial spot of Lady Fatima Masuma, a direct descendent of the Prophet Muhammad, whose death here more than a millennium ago transformed a previously forlorn desert settlement into a pilgrimage site. It became a centre of learning in the 20s, when Shi'ite intellectuals, including Ruhollah Khomeini, began gathering. When he returned from exile in 1979 as Grand Ayatollah Khomeini, he resettled in Qom, from where he led the country's transformation into an Islamic republic, turning the city's seminaries into its ideological engine. Soon there would be 300 madrasas taking in 50,000 students.

Qom was tasked with fomenting Iran's theocratic foreign policy; it became a place much feared by the US and Israel. Both accuse it of being a provocative source of inspiration for students affiliated to extreme groups, including Hezbollah and Hamas, who come to study at the government's expense. Some have also returned to seek sanctuary, including Imad Mughniyah, Hezbollah's special operations chief, spotted in Qom in 2001. He has been accused of masterminding the 1983 bomb attacks on the US embassy and marine barracks in Beirut that killed 304, the 1985 hijacking of TWA flight 847 and numerous kidnappings of westerners in Beirut. More recently, he was blamed for the attack on a Jewish community centre in Buenos Aires in 1994 that left 92 people dead. For these reasons Qom has been identified as a possible target in any US attack.

Ahmadinejad knew that scores of high-ranking clerics would be affronted by his manipulation of the Mahdi story, derisive of his scholarship and critical of what many saw as a cynical attempt to undermine the one man who had the authority to sack him. His claims challenged Grand Ayatollah Ali Khamenei, Iran's Supreme Leader and commander-in-chief, whose official title, vali-e faqih, means "God's jurisprudent on earth" - a direct link with the divine that would be superseded if the Mahdi showed his face.

Although the Supreme Leader had done more than anyone to get the president elected, issuing directives to all Revolutionary Guardsmen and their families to vote for him in 2005, relations soured after Ahmadinejad proved not to be the malleable figure Khamenei had hoped for. Frozen out by the theocratic establishment, Ahmadinejad fought back. He began lambasting many of the city's septuagenarian clerics for being corrupt and soft, reminding people that some had become rich during the Iraq war trading weapons and selling ration cards.

In Qom, Ahmadinejad sought to eclipse long-established seminaries with his own to bring the city under his control. Government money was poured into the Imam Khomeini Institute, a hardline madrasa whose scholars were charged with trawling through religious treatises to find evidence that the Mahdi's re-emergence at Jamkaran was imminent. Ahmadinejad placed in charge Mohammad Taghi Mesbah-Yazdi, a cleric who would soon become known as an ayatollah, a significant promotion without the normal years of study.

Mesbah-Yazdi has become Ahmadinejad's ideological mentor. They first met in the early 80s when Ahmadinejad attended a series of his lectures on the philosopher Martin Heidegger, who had been championed by the Nazis. Here, Ahmadinejad found the noisy, blue-collar nationalism that he would imbue with hyper-spirituality. He created a vision of a pious and soldierly people easing the path of the coming Mahdi.

Abbas Milani, director of Iranian studies at Stanford University in California, who has studied Ahmadinejad's background, explains. "Mesbah-Yazdi forged key elements of an Islamic pseudo-fascist ideology founded on a sour brew of anti-Semitism and Heideggerian philosophy... This in turn has informed Ahmadinejad's world view."

An enthusiastic supporter of the death penalty and public floggings, Mesbah-Yazdi was recently elected to the Assembly of Experts, the body responsible for choosing the next Supreme Leader. He has made it clear he is eyeing the top job.

The ground floor of the Imam Khomeini Iistitute is given over to a large bookshop exclusively selling works by Mesbah-Yazdi. His image is plastered on every wall. Turbaned mullahs enter the building on their way to class. Students come from all over the Muslim world - Pakistan, Afghanistan, Lebanon, Palestine; there are even a handful from America.

A white-bearded ayatollah approaches and asks, "What are you doing here?" After a garbled explanation about wishing to study Islamic law, he introduces himself as Ayatollah Haghani, Yazdi's director of international affairs. He is clearly uncertain, but agrees to show the library where mullahs hunch at study stations, their turbans neatly hanging on a hat-rack in the corner. The shelves are stacked with volumes by Marx, Popper and Russell, and in the periodicals section are anti-terrorism papers produced by Chatham House, in London. The ayatollah's phone trills a Qu'ranic prayer; whoever is on the line is angry that foreigners are here. "You must leave," the ayatollah says curtly. The elevator descends in silence and as the doors open on the ground floor three meaty security guards jump in. Behind them is the unmistakable figure of Mesbah-Yazdi. He brushes past, scowling, in a whirl of coffee-coloured robes. He signals for visitors to be escorted out.

Controlling Qom was only one plank in Ahmadinejad's strategy. As a parvenu, wresting power from the political establishment has been equally important, and he has done it with gusto, filling the cabinet and major administrative bureaucracies with former Revolutionary Guards and intelligence officials. His new intelligence minister is Gholam Hossein Mohseni-Ejehei, a man whom only a little digging reveals has been linked to the murders of Iranian political activists. The new interior minister, Mostafa Pour Mohammadi, sat on a three-person committee in 1988 that ordered the execution of thousands of political prisoners.

Even the culture ministry has been turned upside down. Its new chief is Hossein Saffar Harandi, a university buddy of Ahmadinejad and former Basij leader, whose first act in office was to call upon Iranian musicians to compose a symphony of support for Iran's nuclear programme, and who has shut down almost every newspaper and website critical of the regime. "It's not what they did in the past that matters but what they do in the future," the president has said in defence of his men. This is precisely what worries Shirin Ebadi, the Nobel peace prize-winning Iranian lawyer, who told the Guardian, "The situation in Iran has worsened considerably with these new men in power." Women who complain of rape have been stoned. The age of consent for girls has been lowered to nine. Children have been convicted and executed for adult crimes. Barbers have been jailed for shaving beards.

Yet, for all Ahmadinejad's efforts to control every aspect of Iranian life, his authority has begun slipping away. Some of Iran's most senior clerics have questioned the manipulation of the Mahdi story. Mesbah-Yazdi has been derided as Professor Crocodile (the name Mesbah rhymes with temsah, the Persian word for the reptile), while Ahmadinejad has been accused of "endangering the reputation of Islam and the Qur'an" by Javadi-Amoli, an ayatollah at the Qom seminary school.

But the most damaging criticism comes from Iran's Grand Ayatollahs, a band of 19 leaders whose spiritual authority remains unquestioned. They, too, have become enraged by the upstart in his Revolutionary Guards suit.

At his modest headquarters, Grand Ayatollah Hossein Ali Montazeri, Khomeini's former deputy, sits cross-legged, a skullcap covering his remaining wisps of grey hair. He does not hold back. He accuses the current regime of despotism, over-reliance on Iran's security forces and disrespect for the seminary. "Power brings ignorance, and those in power now have forgotten what the revolution was for." He pauses, aware of the weight of his words. "They have become extremists, going in a different direction."

The Jamkaran extravaganza has enraged the grand ayatollah. "People go expecting to see the Mahdi sitting there in a corner. They are being misled. It is wrong. The Mahdi is very dear to our people and the politicians are taking advantage." He has one more thing to add: "Iran needs to put aside all the bad blood and America needs to stop interfering, before it creates another Iraq or Afghanistan."

At his Qom madrasa, Grand Ayatollah Yusef Saanei has begun to make some startling pronouncements: women having equal rights to men, non-Muslims being treated as respectfully as Muslims, listening to music being permissible, men being allowed to shave their beards. On his wall is a framed quote from Khomeini, saying, "I have raised Mr Saanei like a son of mine."

"America thinks Iran is violent and responsible for all its ills," he says. "It is up to our leaders to show the world the difference between Sunni and Shia Islam, to show Shia Islam has never condoned terrorism and renounces terrorist groups like al-Qaida." Unlike his president, he wants reconciliation. "After Khomeini died, the spirit of what he believed in died away, too. If the current president continues, there will be no new generation." Saanei taps his cane. "If the people now in power carry on, Iran will crumple from the inside and die."

Outside Qom, dissent is building, too. People have begun to question how far Ahmadinejad is prepared to go with his nuclear sabre-rattling and whether the country can defend itself against US "surgical strikes". Among targets already identified by Washington hawks are Revolutionary Guards facilities, many of them in the capital. Last month Jomhuri Eslami, an influential conservative newspaper, chastised the president in a front-page editorial for describing officials who advocated restraint in the nuclear stand-off as "traitors and spies".

However, the most significant threat to Ahmadinejad is his appalling economic record. As soon as he became president, he began increasing state control and destroying the free market. Ministry of finance officials were replaced by clerics with no economic experience; Ayatollah Mesbah-Yazdi was appointed Ahmadinejad's main economic adviser.

Together they have implemented a series of disastrous reforms dictated by the principles of Sharia law. After Mesbah-Yazdi likened banks to loan sharks, Iran's independent banking sector was crippled by a raft of restrictive measures. A low-interest loans scheme for small businesses, designed to encourage job creation, collapsed. Millions have been spent on popular measures, such as the "Love Fund" to help poor young men meet the costs of marriage, and the minimum wage has been increased by 60%. But more than 20% are now out of work and the urban poor, Ahmadinejad's backbone, have been floored by rising prices.

Iran should be one of the richest countries in the world. It is, after all, the fourth largest oil producer and has the second biggest natural gas reserve. But the president has squandered windfall oil revenues on billion-dollar no...#8209;bid contracts awarded to companies owned by friends in the Revolutionary Guards. In the past 18 months, millions of dollars worth of oil revenue is thought to have disappeared into individual pockets as the military has moved seamlessly into building airports, producing oil and opening mobile phone networks, transforming Iran into a military state not unlike its neighbour, Pakistan.

Mohammad Ghouchani, editor of the Hammihan newspaper, says, "Ahmadinejad likes to present himself as Robin Hood, taking from the rich to help the poor, but his scattergun and ill-conceived policies have achieved precisely the opposite." Evidence that this message is sinking in came in September when a poll found that 56% of Ahmadinejad's supporters in 2005 would not turn out for him again. Meanwhile, Hashemi Rafsanjani, the reformist he outwitted in 2005, has gathered strength.

Iran's former ambassador to the UK, Hossein Adeli, has appealed to the west to back down. "This country, this baby of revolution, has been living 30 years in isolation under a deep sense of insecurity, and the majority of Iranians are tired. We are trapped in a wall of deep mistrust and suspicion with the US and UK that has now reached its peak. Our officials and your officials sit in their respective positions issuing rhetoric for their domestic audiences. They're worrying about winning the next election, not communicating with the other side or seeing the ground realities." Adeli should know. Until Ahmadinejad forced him out of office in December 2005, he had been handling secret discussions between Tehran, London and the Bush administration.

What should happen next? "We have to start talking. If we don't, Ahmadinejad will be saved by people who have begun to loathe him. Washington needs to stop, take breath and realise we have many common strategic interests. Iran's most important strength, our weapon, is our influence in the heartland of the world."

Instead of open hostilities, Adeli calls for investment coupled with an offer of unconditional negotiations from Washington. He believes that would provide the impetus for some of the four million wealthy Iranians exiles who took a trillion dollars worth of capital with them to return and launch a campaign for the Islamic Republic's first ever democratic election. It is one that Ahmadinejad would now most likely lose.