#!/usr/bin/env python3
"""
Host a simple Flask server and print the POST of any request to the terminal
"""

from flask import Flask, request

import sys
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdftypes import resolve1
from pdfminer.psparser import PSLiteral
import json
import io

app = Flask(__name__)

# Decode FDF data and print to terminal
@app.route('/', methods=['POST'])
def post():
    data = io.BytesIO(request.data)

    # Decode the data
    parser = PDFParser(data)
    doc = PDFDocument(parser)

    FDF = resolve1(doc.catalog['FDF'])


    fields = resolve1(FDF.get('Fields'))

    for i in fields:
        field = resolve1(i)
        value_psl: PSLiteral | bytes = field.get('V')
        value = ''

        if isinstance(value_psl, PSLiteral):
            if value_psl.name.startswith('\\376\\377'): # Like: \\376\\377\\000p\\000e\\000r\\000s\\000o\\000n
                value = ''.join(
                    c for c in value_psl.name.replace('\\376\\377', '').split('\\000') if c
                )
            else:
                value = value_psl.name
        elif isinstance(value_psl, bytes):
            if value_psl.startswith(b'\xfe\xff'):
                value = value_psl.decode('utf-16-be')
            elif value_psl.startswith(b'\xff\xfe'):
                value = value_psl.decode('utf-16-le')
            else:
                value = value_psl.decode('utf-8')
        else:
            print(f'Unknown type: {type(value_psl)}')

        key = field.get('T').decode('utf-8')

        print(f'{key}: {value}')

    return '', 204

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)