from datetime import datetime
import urllib.request
import urllib.parse
import json
import html

def fetch_changelogs(search_term: str):
    query = urllib.parse.quote(search_term)
    url = f"https://api.ftp-master.debian.org/changelogs?search_term={query}"

    with urllib.request.urlopen(url) as response:
        if response.status != 200:
            raise Exception(f"HTTP Error: {response.status}")
        data = response.read()
        return json.loads(data)

def simplify_date(date_str):
    try:
        dt = datetime.strptime(date_str, "%a, %d %b %Y %H:%M:%S %z")
        return dt.strftime("%Y-%m-%d")
    except ValueError:
        return date_str

def generate_html(data, css_path: str = "style.css"):
    html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Debian Changelogs Search</title>
<link rel="stylesheet" href="{css_path}">
</head>
<body>
<h2>{len(data)} Uploads by Sérgio Cipriano</h2>
<p class="description">
  This table tracks uploads made by me using the dak API. If you want to do
  one for yourself the source code is <a href=".">here</a>. Learn more by
  reading my <a href="https://sergiocipriano.com/dak-changelogs.html">blog
  post</a>.
</p>
<div class="table-wrapper">
  <table>
    <thead>
      <tr>
        <th>Package</th>
        <th>Version</th>
        <th>Date</th>
      </tr>
    </thead>
    <tbody>
"""

    for item in reversed(data):
        # Escape all text content for safety
        package = html.escape(item.get("source", ""))
        version = html.escape(item.get("version", ""))
        date = html.escape(item.get("date", ""))

        html_content += f"""
  <tr>
    <td>{package}</td>
    <td>{version}</td>
    <td>{simplify_date(date)}</td>
  </tr>"""

    html_content += """
      </tbody>
    </table>
  </div>
</body>
</html>
"""
    return html_content

def main():
    search_term = "almeida cipriano"
    try:
        data = fetch_changelogs(search_term)
        html_page = generate_html(data)
        with open("changelogs.html", "w", encoding="utf-8") as f:
            f.write(html_page)
        print("HTML file 'changelogs.html' generated successfully.")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()
