#!/usr/bin/env python3
"""
Generate sitemap.xml for calculator200.com
Run: python3 generate_sitemap.py
"""

import re
import datetime

# ----- CONFIG -----
DOMAIN = "https://calculator200.com"
BLOG_INDEX_FILE = "blog-index.html"          # your existing blog index file
OUTPUT_FILE = "sitemap.xml"

# Add any static pages you want in the sitemap here.
# These are the main entry points.
STATIC_PAGES = [
    "/",
    "/financial-calculator-index.html",
    "/general-calculator-index.html",
    "/science-calculator-index.html",
    "/social-media-index.html",
    "/blog-index.html",
    # A few key calculator pages – add more as needed
    "/financial-calculator/xirr-calculator.html",
    "/financial-calculator/sip-calculator.html",
    "/financial-calculator/emi-calculator.html",
    "/financial-calculator/compound-interest-calculator.html",
    "/general-calculator/age-calculator.html",
    "/general-calculator/bmi-calculator.html",
    "/general-calculator/date-calculator.html",
    "/science-calculator/percentage-calculator.html",
    "/science-calculator/fraction-calculator.html",
    "/social-media/instagram-engagement-rate-calculator.html",
]

# ----- READ BLOG LINKS -----
with open(BLOG_INDEX_FILE, "r", encoding="utf-8") as f:
    html = f.read()

# Extract all hrefs that start with /blog/
blog_links = re.findall(r'href="(/blog/[^"]+)"', html)
# Remove duplicates while keeping order
seen = set()
blog_urls = []
for link in blog_links:
    if link not in seen:
        seen.add(link)
        blog_urls.append(link)

print(f"Found {len(blog_urls)} unique blog posts.")

# ----- BUILD SITEMAP -----
today = datetime.date.today().isoformat()

lines = []
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
lines.append('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')

# Static pages
for page in STATIC_PAGES:
    lines.append("  <url>")
    lines.append(f"    <loc>{DOMAIN}{page}</loc>")
    lines.append(f"    <lastmod>{today}</lastmod>")
    lines.append("    <changefreq>weekly</changefreq>")
    lines.append("    <priority>0.8</priority>")
    lines.append("  </url>")

# Blog posts
for blog in blog_urls:
    lines.append("  <url>")
    lines.append(f"    <loc>{DOMAIN}{blog}</loc>")
    lines.append(f"    <lastmod>{today}</lastmod>")
    lines.append("    <changefreq>monthly</changefreq>")
    lines.append("    <priority>0.6</priority>")
    lines.append("  </url>")

lines.append("</urlset>")

with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
    f.write("\n".join(lines))

print(f"Sitemap written to {OUTPUT_FILE} with {len(STATIC_PAGES) + len(blog_urls)} URLs.")