"""Fetch exchange rates from a free public API (no key) and build a formatted Excel report.
pip install requests openpyxl      then      python api_report.py
API: Frankfurter (ECB reference rates) — https://www.frankfurter.app
"""
from datetime import date, timedelta
import requests
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill
from openpyxl.chart import LineChart, Reference

end = date.today(); start = end - timedelta(days=30)
url = f"https://api.frankfurter.app/{start}..{end}?from=USD&to=INR,EUR,GBP"
resp = requests.get(url, timeout=20)
resp.raise_for_status()                       # stop with a clear error if the API is down
data = resp.json()["rates"]

wb = Workbook(); ws = wb.active; ws.title = "USD rates"
ws.append(["Date", "INR", "EUR", "GBP"])
for c in ws[1]:
    c.font = Font(bold=True, color="FFFFFF"); c.fill = PatternFill("solid", fgColor="217346")
for day in sorted(data):
    r = data[day]; ws.append([day, r.get("INR"), r.get("EUR"), r.get("GBP")])
ws.column_dimensions["A"].width = 12

chart = LineChart(); chart.title = "USD → INR, last 30 days"; chart.height = 8; chart.width = 18
chart.add_data(Reference(ws, min_col=2, min_row=1, max_row=ws.max_row), titles_from_data=True)
chart.set_categories(Reference(ws, min_col=1, min_row=2, max_row=ws.max_row))
ws.add_chart(chart, "F2")
wb.save("usd_rates_report.xlsx")
print("Saved usd_rates_report.xlsx with", ws.max_row - 1, "days")
