"""Example web app that connects to PostgreSQL."""
# Run with: flask --app world run --debug

import psycopg
from flask import Flask
from io import StringIO

app = Flask(__name__)
con = psycopg.connect(host="localhost", 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):
    cur.execute("SELECT name, continent, region, population "
                "FROM country WHERE code = %s", (code,))
    row = cur.fetchone()
    if not row:
        return "<p>Country not found</p>"
    name, cont, reg, pop = row
    out = StringIO()
    out.write(f"<p><b>{name}</b> is in <b>{cont}</b> in the <b>{reg}</b> region.</p>")
    out.write(f"<p><b>{name}</b>'s population <b>{pop:,d}</b>.</p>")
    return out.getvalue()


@app.route("/codes")
def get_codes():
    cur.execute("SELECT Code, Name FROM country")
    out = StringIO()
    out.write("<ul>")
    for code, name in cur:
        out.write(f'<li>{code} = <a href="../country/{code}">{name}</a></li>')
    out.write("</ul>")
    return out.getvalue()
