"""Example web app that connects to PostgreSQL."""

from io import StringIO

import psycopg
from flask import Flask

app = Flask(__name__)
con = psycopg.connect(
    host="data.cs.jmu.edu", user="demo", password="demo", dbname="world"
)
cur = con.cursor()


@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"


@app.route("/country/<code>")
def country_info(code: str):
    _ = cur.execute(
        "SELECT name, continent, region, population FROM country WHERE code = %s",
        (code.upper(),),
    )
    row = cur.fetchone()
    if not row:
        return "<p>Country not found</p>"
    name, cont, reg, pop = row
    out = StringIO()
    _ = out.write(
        f"<p><strong>{name}</strong> is in <strong>{cont}</strong> in the <strong>{reg}</strong> region.</p>"
    )
    _ = out.write(
        f"<p><strong>{name}</strong>'s population <strong>{pop:,d}</strong>.</p>"
    )
    return out.getvalue()


@app.route("/codes")
def multi_country():
    _ = cur.execute("SELECT name, code population FROM country")

    return f"<ul>{"".join(
        f'<li><a href="/country/{code}">{name} {code}</a></li>'
        for (name, code) in cur.fetchall()
    )}</ul>"


if __name__ == "__main__":
    app.run(debug=True)
