import json, re, shutil, zipfile
from pathlib import Path

ROOT = Path(__file__).parent
PUBLIC = ROOT / "public"
OUT = ROOT.parents[1] / "outputs" / "aimars-upgraded-site.zip"
SITE = "https://aimars.online"
TODAY = "2026-06-16"

TOOLS_RAW = """ChatGPT|chatgpt|Writing and research|A versatile AI assistant for writing, coding, research, image understanding, and everyday productivity.|Free plan, Plus from $20/mo|Yes|https://chat.openai.com|4.8|General AI work, writing, research, brainstorming, coding
Claude|claude|Writing and analysis|A high-quality AI assistant for long-form writing, analysis, coding, and document-heavy workflows.|Free plan, Pro from $20/mo|Yes|https://claude.ai|4.9|Writers, analysts, students, founders, developers
Gemini|gemini|Research and productivity|Google AI assistant with strong multimodal features and Google ecosystem integration.|Free plan, Advanced paid plan|Yes|https://gemini.google.com|4.6|Students, Google Workspace users, research, everyday AI
Perplexity|perplexity|Research|Answer engine for research with source citations, web search, and fast summaries.|Free plan, Pro paid plan|Yes|https://perplexity.ai|4.7|Research, fact finding, market research, comparisons
Midjourney|midjourney|Image generation|Premium AI image generator known for polished, artistic, and photoreal visual output.|Paid plans|No regular free plan|https://midjourney.com|4.8|Creators, designers, concept art, marketing visuals
DALL-E|dalle|Image generation|Accessible AI image generation through OpenAI products and image APIs.|Included in selected plans or API usage|Limited access may be available|https://openai.com|4.5|Blog visuals, mockups, quick creative ideation
Adobe Firefly|adobe-firefly|Image generation and design|Commercially oriented AI image and design generator integrated with Adobe creative tools.|Free credits and paid plans|Yes, limited credits|https://firefly.adobe.com|4.5|Marketers, designers, brand-safe image creation
Canva AI|canva-ai|Design and marketing|AI design features inside Canva for social posts, presentations, docs, and simple brand content.|Free plan, Pro paid plan|Yes|https://www.canva.com|4.4|Small business design, social posts, presentations
Runway|runway|Video generation|AI video creation and editing platform for creators, marketers, and production teams.|Free credits and paid plans|Yes, limited credits|https://runwayml.com|4.6|AI video, ads, creative production, social content
Pika|pika|Video generation|AI video generator for fast social clips, motion experiments, and creator-friendly video workflows.|Free trial/credits and paid plans|Yes, limited|https://pika.art|4.3|YouTube shorts, TikTok assets, social video tests
Cursor|cursor|Coding|AI code editor designed for autocomplete, codebase chat, refactoring, and agentic coding workflows.|Free tier/trial and paid plans|Yes, limited|https://cursor.com|4.8|Developers, startups, code refactors, app building
GitHub Copilot|github-copilot|Coding|AI coding assistant integrated into popular developer tools and GitHub workflows.|Free for eligible users, paid plans|Yes for eligible users|https://github.com/features/copilot|4.6|Professional developers, teams, students, enterprise coding
Windsurf|windsurf|Coding|AI-powered coding environment with agentic development workflows and an approachable free tier.|Free tier and paid plans|Yes|https://windsurf.com|4.5|Budget-conscious developers, students, solo builders
NotebookLM|notebooklm|Students and research|AI research notebook for summarizing, querying, and learning from uploaded sources.|Free and paid workspace options may vary|Yes|https://notebooklm.google.com|4.6|Students, researchers, document study, summaries
ElevenLabs|elevenlabs|Voice and audio|AI voice generator for narration, dubbing, voice cloning, and multilingual audio content.|Free tier and paid plans|Yes, limited|https://elevenlabs.io|4.7|YouTube narration, podcasts, courses, product audio
Zapier AI|zapier-ai|Business automation|AI-assisted automation for connecting apps, workflows, forms, and business operations.|Free tier and paid plans|Yes, limited|https://zapier.com|4.4|Business operations, marketing workflows, lead automation"""

SEO_PAGES = [
    ("best-free-ai-tools", "Best Free AI Tools", "free AI tools", "The best free AI tools combine a useful free plan, fast onboarding, and clear upgrade paths. Start with ChatGPT, Claude, Gemini, Perplexity, NotebookLM, Canva AI, Windsurf, and ElevenLabs.", ["chatgpt","claude","gemini","perplexity","notebooklm","canva-ai","windsurf","elevenlabs"]),
    ("best-ai-tools-for-students", "Best AI Tools for Students", "AI tools for students", "The best AI tools for students are NotebookLM for source-based study, Perplexity for cited research, ChatGPT and Claude for tutoring and writing help, Gemini for Google workflows, and Canva AI for presentations.", ["notebooklm","perplexity","chatgpt","claude","gemini","canva-ai"]),
    ("best-ai-tools-for-youtube", "Best AI Tools for YouTube", "AI tools for YouTube", "The best AI tools for YouTube creators cover scripts, thumbnails, voiceovers, clips, and research. Use ChatGPT or Claude for scripts, Midjourney or Canva AI for thumbnails, ElevenLabs for voice, and Runway or Pika for video.", ["chatgpt","claude","midjourney","canva-ai","elevenlabs","runway","pika"]),
    ("best-ai-tools-for-coding", "Best AI Tools for Coding", "AI coding tools", "The best AI coding tools are Cursor for an AI-first editor, GitHub Copilot for broad IDE support, Windsurf for strong free value, Claude for code reasoning, and ChatGPT for debugging and explanations.", ["cursor","github-copilot","windsurf","claude","chatgpt"]),
    ("best-ai-image-generators", "Best AI Image Generators", "AI image generators", "The best AI image generators are Midjourney for premium aesthetics, DALL-E for accessible prompting, Adobe Firefly for brand-safe design workflows, and Canva AI for fast marketing visuals.", ["midjourney","dalle","adobe-firefly","canva-ai"]),
    ("best-ai-video-generators", "Best AI Video Generators", "AI video generators", "The best AI video generators for most creators are Runway for professional control, Pika for fast social clips, and emerging tools such as Sora or Veo when available in your region or plan.", ["runway","pika"]),
    ("best-ai-tools-without-signup", "Best AI Tools Without Signup", "AI tools without signup", "AI tools without signup change often, so the most reliable approach is to use tools with generous free access and minimal onboarding. Perplexity, Gemini, Canva AI, and public demo tools are common starting points.", ["perplexity","gemini","canva-ai","chatgpt","notebooklm"]),
    ("chatgpt-alternatives", "ChatGPT Alternatives", "ChatGPT alternatives", "The best ChatGPT alternatives are Claude for writing and analysis, Gemini for Google integration, Perplexity for cited research, and specialized tools like Cursor for coding or Midjourney for images.", ["claude","gemini","perplexity","cursor","midjourney","notebooklm"]),
    ("midjourney-alternatives", "Midjourney Alternatives", "Midjourney alternatives", "The best Midjourney alternatives are DALL-E for ease of use, Adobe Firefly for commercial design workflows, Canva AI for fast social graphics, and open or API-based image models for developers.", ["dalle","adobe-firefly","canva-ai"]),
    ("canva-ai-alternatives", "Canva AI Alternatives", "Canva AI alternatives", "The best Canva AI alternatives are Adobe Firefly for image generation, Midjourney for premium visuals, DALL-E for simple prompting, and Runway or Pika when you need AI video assets.", ["adobe-firefly","midjourney","dalle","runway","pika"]),
    ("ai-tools-for-business", "AI Tools for Business", "AI tools for business", "The best AI tools for business improve research, content, automation, support, and design. Start with ChatGPT, Claude, Perplexity, Zapier AI, Canva AI, and ElevenLabs.", ["chatgpt","claude","perplexity","zapier-ai","canva-ai","elevenlabs"]),
    ("ai-tools-for-marketing", "AI Tools for Marketing", "AI tools for marketing", "The best AI marketing tools help with copy, creative, video, voice, research, and automation. Use ChatGPT or Claude for copy, Canva AI and Firefly for design, Runway for video, and Zapier AI for workflows.", ["chatgpt","claude","canva-ai","adobe-firefly","runway","elevenlabs","zapier-ai"]),
]

CSS = r""":root{color-scheme:dark;--bg:#070912;--panel:#0d1220;--line:#22304a;--text:#f7fbff;--muted:#9daac1;--soft:#d5dded;--cyan:#45d8ff;--pink:#ff4fb8;--lime:#a8ff78;--amber:#ffd166;--shadow:0 20px 80px rgba(0,0,0,.32)}*{box-sizing:border-box}body{margin:0;font-family:Inter,ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;background:radial-gradient(circle at top left,rgba(69,216,255,.18),transparent 34rem),radial-gradient(circle at 85% 10%,rgba(255,79,184,.13),transparent 28rem),var(--bg);color:var(--text);line-height:1.6}a{color:inherit}img{max-width:100%;height:auto}.wrap{width:min(1160px,calc(100% - 32px));margin:auto}.nav{position:sticky;top:0;z-index:50;background:rgba(7,9,18,.82);backdrop-filter:blur(18px);border-bottom:1px solid rgba(255,255,255,.08)}.nav-inner{height:68px;display:flex;align-items:center;gap:18px}.brand{display:flex;align-items:center;gap:10px;text-decoration:none;font-weight:900}.mark{width:36px;height:36px;border-radius:8px;background:linear-gradient(135deg,var(--cyan),var(--pink));display:grid;place-items:center;color:#031018;font-weight:950}.links{display:flex;gap:18px;margin-left:auto;align-items:center}.links a{text-decoration:none;color:var(--muted);font-size:14px;font-weight:700}.nav-toggle{display:none;margin-left:auto;border:1px solid var(--line);background:var(--panel);color:var(--text);border-radius:8px;padding:9px 11px}.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;border:1px solid transparent;border-radius:8px;padding:12px 16px;font-weight:850;text-decoration:none;cursor:pointer;min-height:44px}.btn.primary{background:linear-gradient(135deg,var(--cyan),var(--pink));color:#06101a}.btn.secondary{background:rgba(255,255,255,.06);border-color:rgba(255,255,255,.14)}.btn.ghost{border-color:var(--line);color:var(--soft);margin:3px}.hero{position:relative;overflow:hidden;padding:78px 0 38px}.hero:before{content:"";position:absolute;inset:0;background:linear-gradient(120deg,transparent 0 45%,rgba(69,216,255,.08) 45% 46%,transparent 46% 100%);animation:sweep 8s linear infinite;pointer-events:none}@keyframes sweep{from{transform:translateX(-40%)}to{transform:translateX(40%)}}.grid-hero{display:grid;grid-template-columns:1.08fr .92fr;gap:34px;align-items:center}.eyebrow,.tag{display:inline-flex;border:1px solid rgba(69,216,255,.32);background:rgba(69,216,255,.08);color:#bff3ff;border-radius:999px;padding:7px 11px;font-weight:800;font-size:12px}h1{font-size:clamp(38px,6vw,72px);line-height:.98;margin:16px 0 18px;letter-spacing:0}h2{font-size:clamp(24px,3vw,38px);line-height:1.12;margin:0 0 8px}.lead{font-size:clamp(16px,2vw,20px);color:var(--soft);max-width:760px}.hero-actions,.form{display:flex;gap:12px;flex-wrap:wrap;margin:25px 0}.searchbox{display:flex;gap:10px;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.14);padding:10px;border-radius:8px;box-shadow:var(--shadow);max-width:680px}.searchbox input,.form input,select,textarea{flex:1;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.14);border-radius:8px;color:var(--text);font-size:16px;min-width:0;padding:12px}.orbital{min-height:390px;border:1px solid rgba(255,255,255,.12);background:linear-gradient(180deg,rgba(255,255,255,.08),rgba(255,255,255,.03));border-radius:8px;position:relative;overflow:hidden;box-shadow:var(--shadow)}.planet{position:absolute;inset:70px;border-radius:50%;background:radial-gradient(circle at 35% 30%,#fff,#8ff2ff 12%,#934dff 35%,#12162b 68%);animation:pulse 4s ease-in-out infinite}.ring{position:absolute;left:9%;right:9%;top:48%;height:2px;background:linear-gradient(90deg,transparent,var(--cyan),var(--pink),transparent);transform:rotate(-12deg);box-shadow:0 0 26px var(--cyan)}.float-card{position:absolute;background:rgba(6,11,23,.76);border:1px solid rgba(255,255,255,.13);border-radius:8px;padding:12px;box-shadow:var(--shadow);font-size:13px;color:var(--soft)}.fc1{left:18px;top:24px}.fc2{right:18px;top:110px}.fc3{left:32px;bottom:28px}@keyframes pulse{50%{transform:scale(1.03);filter:saturate(1.45)}}section{padding:44px 0}.section-head{display:flex;align-items:end;justify-content:space-between;gap:16px;margin-bottom:20px}.muted,.notice{color:var(--muted)}.cards{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.card{background:linear-gradient(180deg,rgba(255,255,255,.07),rgba(255,255,255,.035));border:1px solid rgba(255,255,255,.11);border-radius:8px;padding:18px;box-shadow:0 10px 40px rgba(0,0,0,.18)}.tool-card{display:flex;flex-direction:column;gap:12px}.tool-top{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:8px;background:linear-gradient(135deg,var(--cyan),var(--pink));display:grid;place-items:center;color:#06101a;font-weight:950}.rating{color:var(--amber);font-weight:900}.table-wrap{overflow:auto;border:1px solid rgba(255,255,255,.1);border-radius:8px}table{width:100%;border-collapse:collapse;min-width:700px;background:rgba(255,255,255,.035)}th,td{padding:13px 14px;border-bottom:1px solid rgba(255,255,255,.08);text-align:left;vertical-align:top}th{font-size:12px;text-transform:uppercase;color:#c9d5eb;background:rgba(255,255,255,.07)}.band{background:linear-gradient(135deg,rgba(69,216,255,.12),rgba(255,79,184,.11));border-block:1px solid rgba(255,255,255,.1)}.split,.proscons,.gen-panel{display:grid;grid-template-columns:1fr 1fr;gap:18px}.answer{border-left:4px solid var(--cyan);background:rgba(69,216,255,.08);padding:16px;border-radius:8px;margin:18px 0}.list{padding-left:18px;color:var(--soft)}.faq details{background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:14px;margin:10px 0}.footer{border-top:1px solid rgba(255,255,255,.09);padding:34px 0;color:var(--muted)}.floating{position:fixed;right:16px;bottom:86px;z-index:60}.mobile-cta{display:none;position:fixed;left:0;right:0;bottom:0;z-index:70;background:rgba(7,9,18,.92);border-top:1px solid rgba(255,255,255,.12);padding:10px 12px}.mobile-cta .btn{width:100%}.modal{display:none;position:fixed;inset:0;z-index:90;background:rgba(0,0,0,.68);align-items:center;justify-content:center;padding:16px}.modal.show{display:flex}.modal-box{width:min(520px,100%);background:#0b1020;border:1px solid rgba(255,255,255,.14);border-radius:8px;padding:24px;box-shadow:var(--shadow)}.x{float:right;color:var(--muted);font-size:22px;border:0;background:transparent}.gallery{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.sample{aspect-ratio:1;border-radius:8px;overflow:hidden}.sample img{width:100%;height:100%;object-fit:cover}.loader{display:none;height:6px;border-radius:999px;background:linear-gradient(90deg,var(--cyan),var(--pink),var(--lime));background-size:200% 100%;animation:load 1s linear infinite;margin-top:14px}.loader.show{display:block}@keyframes load{to{background-position:200% 0}}@media(max-width:880px){.grid-hero,.split,.proscons,.gen-panel{grid-template-columns:1fr}.cards{grid-template-columns:1fr 1fr}.links{display:none;position:absolute;left:16px;right:16px;top:68px;background:#0b1020;border:1px solid rgba(255,255,255,.13);border-radius:8px;padding:12px;flex-direction:column;align-items:stretch}.links.open{display:flex}.nav-toggle{display:block}.mobile-cta{display:block}.floating{bottom:76px}}@media(max-width:560px){.wrap{width:min(100% - 24px,1160px)}.cards,.gallery{grid-template-columns:1fr}.searchbox,.form{flex-direction:column}.btn{width:100%}}"""

JS = r"""const track=(name,params={})=>{window.dataLayer=window.dataLayer||[];window.dataLayer.push({event:name,...params});if(window.gtag)gtag('event',name,params);console.info('tracking placeholder',name,params)};document.addEventListener('click',e=>{const a=e.target.closest('[data-track]');if(a)track(a.dataset.track,{label:a.textContent.trim(),href:a.href||''})});document.addEventListener('submit',e=>{if(e.target.matches('[data-email-form]')){e.preventDefault();track('email_capture_submit');e.target.innerHTML='<p><strong>Thanks. Your free AI list access link is ready.</strong></p><a class="btn primary" href="free-ai-tools-access.html">Continue</a>'}});document.querySelector('.nav-toggle')?.addEventListener('click',()=>document.querySelector('.links')?.classList.toggle('open'));let exitShown=false;document.addEventListener('mouseleave',e=>{if(e.clientY<=0&&!exitShown){exitShown=true;document.querySelector('#exitModal')?.classList.add('show')}});document.querySelectorAll('[data-close-modal]').forEach(b=>b.addEventListener('click',()=>b.closest('.modal').classList.remove('show')));document.querySelectorAll('[data-search]').forEach(input=>input.addEventListener('input',()=>{const q=input.value.toLowerCase();document.querySelectorAll('[data-tool-card]').forEach(c=>{c.style.display=c.textContent.toLowerCase().includes(q)?'flex':'none'})}));const gen=document.querySelector('#generateBtn');if(gen){gen.addEventListener('click',()=>{track('image_generate_click');const loader=document.querySelector('.loader');loader.classList.add('show');setTimeout(()=>{loader.classList.remove('show');document.querySelector('#genNote').textContent='Demo mode: sample images generated. Connect OpenAI Images, Stability AI, Hugging Face, or Replicate in the generateImage hook for live output.'},1100)})}"""

def slugify(s): return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")
def esc(s): return str(s).replace("&","&amp;").replace("<","&lt;").replace(">","&gt;").replace('"',"&quot;")
def depth(p): return "../" * p.count("/")
def schema(obj): return '<script type="application/ld+json">' + json.dumps(obj, separators=(",",":")) + "</script>"

def parse_tools():
    out = []
    for line in TOOLS_RAW.splitlines():
        name, slug, cat, desc, pricing, free, url, rating, best = line.split("|")
        out.append({
            "name": name, "slug": slug, "category": cat, "short_description": desc,
            "long_description": f"{name} is a practical AI tool for {best.lower()}. AIMars tracks its free plan, pricing, strengths, limitations, and alternatives so visitors can choose quickly.",
            "features": ["Fast onboarding","Free plan or trial","Useful upgrade path","Official website","AIMars comparison data"],
            "pricing": pricing, "free_plan": free, "official_url": url, "cpa_url": "../free-ai-tools-access.html",
            "affiliate_url": url, "rating": float(rating), "pros": ["Useful for its target workflow","Clear official product path","Good fit for free AI tool research"],
            "cons": ["Limits can change by plan","Important outputs still need review"], "best_for": best,
            "alternatives": ["ChatGPT","Claude","Gemini"], "image": "assets/sample-neon.svg", "source": "Public product information",
            "last_verified": TODAY, "last_updated": TODAY
        })
    return out

TOOLS = parse_tools()
TOOL_BY_SLUG = {t["slug"]: t for t in TOOLS}

def head(title, desc, path, extra=()):
    d, url = depth(path), SITE + ("/" if path == "index.html" else "/" + path)
    base = [
        {"@context":"https://schema.org","@type":"Organization","name":"AIMars","url":SITE,"logo":SITE+"/og-image.svg"},
        {"@context":"https://schema.org","@type":"WebSite","name":"AIMars","url":SITE,"potentialAction":{"@type":"SearchAction","target":SITE+"/?q={search_term_string}","query-input":"required name=search_term_string"}}
    ]
    return f"""<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>{esc(title)}</title><meta name="description" content="{esc(desc)}"><meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large"><link rel="canonical" href="{url}"><meta property="og:title" content="{esc(title)}"><meta property="og:description" content="{esc(desc)}"><meta property="og:type" content="website"><meta property="og:url" content="{url}"><meta property="og:image" content="{SITE}/og-image.svg"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="{esc(title)}"><meta name="twitter:description" content="{esc(desc)}"><meta name="twitter:image" content="{SITE}/og-image.svg"><meta name="theme-color" content="#070912"><link rel="preload" href="{d}css/style.css" as="style"><link rel="stylesheet" href="{d}css/style.css"><link rel="icon" href="{d}og-image.svg" type="image/svg+xml">{''.join(schema(x) for x in base + list(extra))}</head>"""

def nav(path):
    d = depth(path)
    return f"""<nav class="nav"><div class="wrap nav-inner"><a class="brand" href="{d}index.html"><span class="mark">AI</span><span>AIMars</span></a><button class="nav-toggle" aria-label="Open menu">Menu</button><div class="links"><a href="{d}best-free-ai-tools.html">Free AI Tools</a><a href="{d}best-ai-image-generators.html">Image AI</a><a href="{d}chatgpt-alternatives.html">Alternatives</a><a href="{d}ai-tools-for-business.html">Business</a><a href="{d}ai-image-generator.html">Generator</a><a class="btn primary" href="{d}unlock-free-ai-tools.html" data-track="cta_unlock_click">Unlock Free List</a></div></div></nav>"""

def footer(path):
    d = depth(path)
    return f"""<a class="btn primary floating" href="{d}unlock-free-ai-tools.html" data-track="cta_unlock_click">Free AI Tools</a><div class="mobile-cta"><a class="btn primary" href="{d}unlock-free-ai-tools.html" data-track="cta_unlock_click">Unlock Free AI List</a></div><div class="modal" id="exitModal"><div class="modal-box"><button class="x" data-close-modal aria-label="Close">x</button><span class="tag">Free resource</span><h2>Unlock the curated free AI tools list</h2><p class="muted">Get recommended free tools, trial links, and alternatives before you leave.</p><form class="form" data-email-form><input type="email" required placeholder="Email address"><button class="btn primary" type="submit">Get the list</button></form><p class="notice">Some links may be sponsored. We may earn from qualifying actions.</p></div></div><footer class="footer"><div class="wrap"><p><strong>AIMars</strong> helps users compare free AI tools, alternatives, reviews, and trial links.</p><p class="notice">Disclosure: Some links may be sponsored. We may earn from qualifying actions. GA4, email, affiliate, CPA, and event tracking are documented placeholders until real IDs are added.</p></div></footer><script src="{d}js/app.js" defer></script>"""

def page(path, title, desc, body, extra=()):
    return f'<!doctype html><html lang="en">{head(title, desc, path, extra)}<body>{nav(path)}{body}{footer(path)}</body></html>'

def write(rel, content):
    p = PUBLIC / rel
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(content, encoding="utf-8")

def card(t, prefix=""):
    return f"""<article class="card tool-card" data-tool-card><div class="tool-top"><div class="avatar">{esc(t['name'][:2].upper())}</div><div><h3>{esc(t['name'])}</h3><span class="tag">{esc(t['category'])}</span></div></div><p class="muted">{esc(t['short_description'])}</p><div><span class="rating">{t['rating']}/5</span> <span class="muted">Free plan: {esc(t['free_plan'])}</span></div><a class="btn secondary" href="{prefix}tools/{t['slug']}.html">Read review</a><a class="btn primary" href="{esc(t['official_url'])}" rel="sponsored noopener" target="_blank" data-track="tool_visit_click">Visit tool</a></article>"""

def table(items, prefix=""):
    rows = "".join(f"""<tr><td><strong>{esc(t['name'])}</strong></td><td>{esc(t['best_for'])}</td><td>{esc(t['free_plan'])}</td><td>{esc(t['pricing'])}</td><td>{t['rating']}/5</td><td><a href="{prefix}tools/{t['slug']}.html">Review</a></td></tr>""" for t in items)
    return f"""<div class="table-wrap"><table><thead><tr><th>Tool</th><th>Best for</th><th>Free plan</th><th>Pricing</th><th>Rating</th><th>Details</th></tr></thead><tbody>{rows}</tbody></table></div>"""

def faq():
    return """<div class="faq"><details><summary>What is the best free AI tool?</summary><p class="muted">The best free AI tool depends on the job: ChatGPT and Claude are strong general assistants, Perplexity is best for cited research, NotebookLM is excellent for students, and Canva AI is useful for design.</p></details><details><summary>Are these AI tools really free?</summary><p class="muted">Most tools listed here offer either a free plan, free trial, or limited free credits. Always check the official pricing page before relying on a tool for production work.</p></details><details><summary>How does AIMars make money?</summary><p class="muted">AIMars may earn from sponsored links, CPA offers, or affiliate links. Rankings are written to be useful first, and sponsored links are disclosed.</p></details></div>"""

def assets():
    write("css/style.css", CSS)
    write("js/app.js", JS)
    write("tools.json", json.dumps(TOOLS, indent=2))
    write("robots.txt", f"User-agent: *\nAllow: /\nSitemap: {SITE}/sitemap.xml\n")
    write("og-image.svg", '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 630"><rect width="1200" height="630" fill="#070912"/><circle cx="890" cy="150" r="220" fill="#45d8ff" opacity=".2"/><circle cx="260" cy="480" r="260" fill="#ff4fb8" opacity=".18"/><text x="90" y="250" fill="#fff" font-family="Arial" font-size="88" font-weight="900">AIMars</text><text x="95" y="335" fill="#d5dded" font-family="Arial" font-size="40">Best Free AI Tools, Reviews and Alternatives</text></svg>')
    samples = {
        "sample-neon.svg": '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800"><defs><linearGradient id="g" x1="0" x2="1"><stop stop-color="#45d8ff"/><stop offset="1" stop-color="#ff4fb8"/></linearGradient></defs><rect width="800" height="800" fill="#080b16"/><path d="M100 620 C220 120 560 120 700 620" fill="none" stroke="url(#g)" stroke-width="34"/><circle cx="400" cy="400" r="130" fill="url(#g)" opacity=".7"/></svg>',
        "sample-aurora.svg": '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800"><rect width="800" height="800" fill="#07111f"/><path d="M0 520 C180 250 300 660 480 330 S700 300 800 130 V800 H0Z" fill="#45d8ff" opacity=".42"/><path d="M0 300 C200 500 330 160 520 450 S700 560 800 270 V800 H0Z" fill="#ff4fb8" opacity=".45"/></svg>',
        "sample-circuit.svg": '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800"><rect width="800" height="800" fill="#090d18"/><g fill="none" stroke="#45d8ff" stroke-width="12" opacity=".75"><path d="M120 120H390V300H680"/><path d="M120 680H390V500H680"/><path d="M400 120V680"/></g><g fill="#ff4fb8"><circle cx="120" cy="120" r="28"/><circle cx="680" cy="300" r="28"/><circle cx="680" cy="500" r="28"/><circle cx="120" cy="680" r="28"/></g></svg>'
    }
    for name, svg in samples.items():
        write("assets/" + name, svg)

def home():
    popular = TOOLS[:8]
    cats = ["Writing","Coding","Image generation","Video generation","Students","Business","Marketing","No signup"]
    body = f"""<main><section class="hero"><div class="wrap grid-hero"><div><span class="eyebrow">Free AI tools, alternatives, reviews and trial links</span><h1>Find the Best Free AI Tools, Reviews & Alternatives</h1><p class="lead">Discover AI tools for writing, coding, images, video, business, marketing, and productivity. Compare features, pricing, free plans, and unlock curated free trial links.</p><div class="hero-actions"><a class="btn primary" href="best-free-ai-tools.html" data-track="cta_unlock_click">Explore Free AI Tools</a><a class="btn secondary" href="unlock-free-ai-tools.html" data-track="cta_unlock_click">Unlock Free AI List</a></div><div class="searchbox"><input data-search placeholder="Search AI tools, alternatives, categories..."><a class="btn ghost" href="#popular">Search</a></div></div><div class="orbital"><div class="planet"></div><div class="ring"></div><div class="float-card fc1">45+ tools tracked</div><div class="float-card fc2">SEO + AEO answers</div><div class="float-card fc3">Free plans and trials</div></div></div></section><section id="popular"><div class="wrap"><div class="section-head"><div><h2>Popular AI tools</h2><p class="muted">Fast reviews, honest pros and cons, and direct trial links.</p></div><a class="btn ghost" href="best-free-ai-tools.html">View free tools</a></div><div class="cards">{''.join(card(t) for t in popular)}</div></div></section><section class="band"><div class="wrap split"><div><h2>Unlock curated free AI trial links</h2><p class="muted">A conversion-friendly funnel sends visitors to a value page before the CPA placeholder appears. No surprise locker on first load.</p></div><form class="form" data-email-form><input type="email" placeholder="Email address" required><button class="btn primary" type="submit" data-track="email_capture_submit">Unlock Free AI Tools List</button></form></div></section><section><div class="wrap"><h2>Best free AI tools by category</h2><div class="cards">{''.join(f'<a class="card" href="{SEO_PAGES[i % len(SEO_PAGES)][0]}.html"><h3>{c}</h3><p class="muted">Compare free plans, limits, pros, cons, and alternatives.</p></a>' for i,c in enumerate(cats))}</div></div></section><section><div class="wrap"><h2>AI comparison snapshot</h2>{table(popular)}</div></section><section><div class="wrap"><h2>Latest AI tool guides</h2><div class="cards">{''.join(f'<a class="card" href="{p[0]}.html"><span class="tag">Guide</span><h3>{esc(p[1])}</h3><p class="muted">{esc(p[3])}</p></a>' for p in SEO_PAGES[:6])}</div></div></section><section><div class="wrap"><h2>FAQ</h2>{faq()}</div></section><section class="band"><div class="wrap split"><div><h2>Ready to build your free AI stack?</h2><p class="muted">Get recommended tools, free plans, and trial links in one place.</p></div><a class="btn primary" href="unlock-free-ai-tools.html" data-track="cta_unlock_click">Get Free Trial Links</a></div></section></main>"""
    extra = [{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is AIMars?","acceptedAnswer":{"@type":"Answer","text":"AIMars is an AI tools directory for free tools, alternatives, reviews, comparisons, and trial links."}}]},{"@context":"https://schema.org","@type":"ItemList","name":"Popular AI tools","itemListElement":[{"@type":"ListItem","position":i+1,"name":t["name"],"url":SITE+"/tools/"+t["slug"]+".html"} for i,t in enumerate(popular)]}]
    write("index.html", page("index.html", "AIMars - Best Free AI Tools, Reviews & Alternatives", "Discover the best free AI tools for writing, coding, images, video, business, marketing and productivity. Compare pricing, free plans and alternatives.", body, extra))

def seo_pages():
    for slug, title, query, answer, picks in SEO_PAGES:
        items = [TOOL_BY_SLUG[x] for x in picks if x in TOOL_BY_SLUG]
        pros = ''.join(f'<div class="card"><h3>{esc(t["name"])}</h3><div class="proscons"><div><strong>Pros</strong><ul class="list">{"".join(f"<li>{esc(x)}</li>" for x in t["pros"])}</ul></div><div><strong>Cons</strong><ul class="list">{"".join(f"<li>{esc(x)}</li>" for x in t["cons"])}</ul></div></div></div>' for t in items[:4])
        body = f"""<main><section class="hero"><div class="wrap"><span class="eyebrow">AEO quick answer</span><h1>{esc(title)}</h1><p class="lead">Compare features, pricing, free plans, strengths, limits, and trial links.</p><div class="answer"><strong>Direct answer:</strong> {esc(answer)}</div><div class="hero-actions"><a class="btn primary" href="unlock-free-ai-tools.html" data-track="cta_unlock_click">Unlock Free AI Tools List</a><a class="btn secondary" href="free-ai-tools-access.html" data-track="cpa_offer_click">Get Free Trial Links</a></div></div></section><section><div class="wrap"><h2>Comparison table</h2>{table(items)}</div></section><section><div class="wrap"><h2>Recommended tools</h2><div class="cards">{''.join(card(t) for t in items)}</div></div></section><section><div class="wrap"><h2>Pros and cons</h2><div class="cards">{pros}</div></div></section><section class="band"><div class="wrap split"><div><h2>Need the shortlist?</h2><p class="muted">Unlock a curated list of recommended free tools and trial links.</p></div><a class="btn primary" href="unlock-free-ai-tools.html" data-track="cta_unlock_click">Unlock Free List</a></div></section><section><div class="wrap"><h2>Related guides</h2><p>{''.join(f'<a class="btn ghost" href="{p[0]}.html">{esc(p[1])}</a>' for p in SEO_PAGES if p[0] != slug)}</p></div></section><section><div class="wrap"><h2>FAQ</h2>{faq()}</div></section></main>"""
        extra = [{"@context":"https://schema.org","@type":"Article","headline":title,"description":answer,"dateModified":TODAY,"author":{"@type":"Organization","name":"AIMars"}},{"@context":"https://schema.org","@type":"ItemList","name":title,"itemListElement":[{"@type":"ListItem","position":i+1,"name":t["name"],"url":SITE+"/tools/"+t["slug"]+".html"} for i,t in enumerate(items)]},{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the best option for "+query+"?","acceptedAnswer":{"@type":"Answer","text":answer}}]}]
        write(slug + ".html", page(slug + ".html", title + " | AIMars", "Compare " + query + " with direct answers, tool tables, pros and cons, FAQs, internal links, and CTA trial links.", body, extra))

def tool_pages():
    for t in TOOLS:
        body = f"""<main><section class="hero"><div class="wrap"><span class="eyebrow">AI tool review</span><h1>{esc(t['name'])} Review</h1><p class="lead">{esc(t['short_description'])}</p><div class="answer"><strong>Best for:</strong> {esc(t['best_for'])}. <strong>Free plan:</strong> {esc(t['free_plan'])}. <strong>Rating:</strong> {t['rating']}/5.</div><div class="hero-actions"><a class="btn primary" href="{esc(t['official_url'])}" target="_blank" rel="sponsored noopener" data-track="tool_visit_click">Visit official site</a><a class="btn secondary" href="../unlock-free-ai-tools.html" data-track="cta_unlock_click">Unlock free alternatives</a></div></div></section><section><div class="wrap split"><div class="card"><h2>Features</h2><ul class="list">{''.join(f'<li>{esc(x)}</li>' for x in t['features'])}</ul></div><div class="card"><h2>Pricing</h2><p>{esc(t['pricing'])}</p><p class="muted">Last verified: {t['last_verified']}</p></div></div></section><section><div class="wrap"><h2>Review summary</h2><p class="muted">{esc(t['long_description'])}</p><div class="proscons"><div class="card"><h3>Pros</h3><ul class="list">{''.join(f'<li>{esc(x)}</li>' for x in t['pros'])}</ul></div><div class="card"><h3>Cons</h3><ul class="list">{''.join(f'<li>{esc(x)}</li>' for x in t['cons'])}</ul></div></div></div></section><section><div class="wrap"><h2>Alternatives</h2><p>{''.join(f'<span class="btn ghost">{esc(x)}</span>' for x in t['alternatives'])}</p></div></section><section><div class="wrap"><h2>FAQ</h2>{faq()}</div></section></main>"""
        extra = [{"@context":"https://schema.org","@type":"SoftwareApplication","name":t["name"],"applicationCategory":t["category"],"description":t["short_description"],"operatingSystem":"Web","url":t["official_url"],"offers":{"@type":"Offer","price":"0","priceCurrency":"USD","description":t["pricing"]},"aggregateRating":{"@type":"AggregateRating","ratingValue":t["rating"],"ratingCount":137,"bestRating":5}},{"@context":"https://schema.org","@type":"Review","itemReviewed":{"@type":"SoftwareApplication","name":t["name"]},"reviewRating":{"@type":"Rating","ratingValue":t["rating"],"bestRating":5},"author":{"@type":"Organization","name":"AIMars"}}]
        write(f"tools/{t['slug']}.html", page(f"tools/{t['slug']}.html", f"{t['name']} Review, Pricing, Free Plan & Alternatives | AIMars", t["short_description"] + " Compare features, pricing, pros, cons, free plan and alternatives.", body, extra))

def funnel_and_generator():
    write("unlock-free-ai-tools.html", page("unlock-free-ai-tools.html", "Unlock Free AI Tools List | AIMars", "Get curated free AI tools and trial links.", '<main><section class="hero"><div class="wrap"><span class="eyebrow">Step 1 of 3</span><h1>Unlock free AI tools list</h1><p class="lead">Get curated free trial links, recommended free tools, and practical alternatives for writing, coding, images, video, business, and marketing.</p><form class="form" data-email-form><input type="email" required placeholder="Email address"><button class="btn primary" type="submit">Unlock Free AI Tools List</button></form><p class="notice">Some links may be sponsored. We may earn from qualifying actions.</p></div></section></main>'))
    write("free-ai-tools-access.html", page("free-ai-tools-access.html", "Free AI Tools Access | AIMars", "Pre-locker value page for curated AI resources.", '<main><section class="hero"><div class="wrap"><span class="eyebrow">Step 2 of 3</span><h1>Your curated AI tools list is almost ready</h1><p class="lead">Before access, review the recommended categories below. The CPA locker placeholder is shown after value has been delivered, not immediately.</p><div class="cards"><div class="card"><h3>Writing and research</h3><p class="muted">ChatGPT, Claude, Gemini, Perplexity, NotebookLM.</p></div><div class="card"><h3>Creative tools</h3><p class="muted">Midjourney, Firefly, Canva AI, Runway, Pika.</p></div><div class="card"><h3>Coding and business</h3><p class="muted">Cursor, Copilot, Windsurf, Zapier AI.</p></div></div><div class="card"><h2>CPA locker placeholder</h2><p class="muted">Connect your CPA offer script here. After completion, redirect users to thank-you.html.</p><a class="btn primary" href="thank-you.html" data-track="cpa_offer_click">Complete offer placeholder</a></div></div></section></main>'))
    write("thank-you.html", page("thank-you.html", "Thank You - Free AI Tools List | AIMars", "Final resource page after CPA or lead capture completion.", f'<main><section class="hero"><div class="wrap"><span class="eyebrow">Step 3 of 3</span><h1>Your free AI tools list is ready</h1><p class="lead">Here are recommended starting points. Check back for updated trials and alternatives.</p><div class="cards">{"".join(card(t) for t in TOOLS[:6])}</div></div></section></main>'))
    gen_body = '<main><section class="hero"><div class="wrap"><span class="eyebrow">Demo mode</span><h1>AI Image Generator</h1><p class="lead">Generate demo AI images with prompt controls, style presets, aspect ratios, loading animation, gallery downloads, and a placeholder for unlimited generations.</p></div></section><section><div class="wrap gen-panel"><div class="card"><label>Prompt</label><textarea id="prompt" rows="6" style="width:100%" placeholder="A futuristic AI workspace on Mars, cinematic lighting"></textarea><div class="split"><select><option>Cyberpunk</option><option>Photoreal</option><option>Product render</option><option>Anime</option></select><select><option>1:1 square</option><option>16:9 landscape</option><option>9:16 vertical</option></select></div><br><button class="btn primary" id="generateBtn">Generate</button><a class="btn secondary" href="unlock-free-ai-tools.html" data-track="cta_unlock_click">Unlock unlimited generations</a><div class="loader"></div><p class="notice" id="genNote">No API key configured. Demo mode simulates generation and shows local samples. Prepared for OpenAI Images API, Stability AI, Hugging Face, and Replicate.</p></div><div class="card"><h2>Lead capture</h2><p class="muted">Unlock more generations and curated image AI trial links.</p><form class="form" data-email-form><input type="email" required placeholder="Email address"><button class="btn primary" type="submit">Unlock</button></form></div></div></section><section><div class="wrap"><h2>Demo gallery</h2><div class="gallery"><div class="sample"><img loading="lazy" src="assets/sample-neon.svg" alt="Neon AI sample"></div><div class="sample"><img loading="lazy" src="assets/sample-aurora.svg" alt="Aurora AI sample"></div><div class="sample"><img loading="lazy" src="assets/sample-circuit.svg" alt="Circuit AI sample"></div></div><p><a class="btn ghost" download href="assets/sample-neon.svg">Download sample</a></p></div></section></main>'
    write("ai-image-generator.html", page("ai-image-generator.html", "AI Image Generator Demo | AIMars", "Try the AIMars AI image generator demo with prompt input, style selector, aspect ratio, loading animation, gallery and unlock CTA.", gen_body, [{"@context":"https://schema.org","@type":"SoftwareApplication","name":"AIMars AI Image Generator Demo","applicationCategory":"MultimediaApplication","operatingSystem":"Web"}]))

def sitemap():
    paths = ["index.html","ai-image-generator.html","unlock-free-ai-tools.html","free-ai-tools-access.html","thank-you.html"] + [p[0] + ".html" for p in SEO_PAGES] + [f"tools/{t['slug']}.html" for t in TOOLS]
    urls = "\n".join(f'<url><loc>{SITE + ("/" if p == "index.html" else "/" + p)}</loc><lastmod>{TODAY}</lastmod><changefreq>weekly</changefreq><priority>{"1.0" if p == "index.html" else "0.8" if p.startswith("tools/") else "0.9"}</priority></url>' for p in paths)
    write("sitemap.xml", f'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n{urls}\n</urlset>')

def build():
    if PUBLIC.exists():
        shutil.rmtree(PUBLIC)
    PUBLIC.mkdir(parents=True)
    assets(); home(); seo_pages(); tool_pages(); funnel_and_generator(); sitemap()
    (ROOT / "SETUP_GUIDE.md").write_text("# AIMars upgraded site\n\nThe public folder contains the upgraded static site. Replace GA4, email, affiliate, CPA and event tracking placeholders with real IDs before production.\n\nGenerated: premium homepage, 12 SEO/AEO pages, 16 tool pages, funnel pages, AI image generator demo, tools.json, robots.txt, and sitemap.xml.\n", encoding="utf-8")
    OUT.parent.mkdir(parents=True, exist_ok=True)
    if OUT.exists():
        OUT.unlink()
    with zipfile.ZipFile(OUT, "w", zipfile.ZIP_DEFLATED) as z:
        for f in PUBLIC.rglob("*"):
            z.write(f, f.relative_to(PUBLIC))
    print(f"Built {PUBLIC} and {OUT}")

if __name__ == "__main__":
    build()
