#!/usr/pkg/bin/python3

import os
import sys

if 'page' not in os.environ['QUERY_STRING']:
   with open('info') as f:
       for line in f:
           print("i{}\t".format(line.strip()))
   print("0The source of this script\t/users/bej/wikisummary/wikisummary.py")
   sys.exit()

import requests
import textwrap
from itertools import chain
headers = {'User-Agent': 'Gopher Wiki Summarizer (by [email protected])'}

query = {split[0]: split[1] for split in [entry.split('=') for entry in os.environ['QUERY_STRING'].split('&')]}
r = requests.get('https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles={}&explaintext=1&exsectionformat=wiki'.format(query['page']))
key = list(r.json()['query']['pages'].keys())[0]
paragraphs = r.json()['query']['pages'][key]['extract'].replace('==\n', '==\n\n').split('\n\n')
formatted = [textwrap.wrap(paragraph, drop_whitespace=True) + [''] for paragraph in paragraphs]
print("\n".join(["i{}\t".format(line) for line in chain.from_iterable(formatted[:8])]))
if len(formatted) > 8:
   print("iOutput was too long, full page can be found here\t")
   print("h{}\tURL:https://en.wikipedia.org/wiki/{}".format(query['page'], query['page']))