from flask import Flask, request
from flask_cors import CORS

import requests
from bs4 import BeautifulSoup
import re
import json

app = Flask(__name__)
CORS(app)

@app.route("/recipe_manager_register")
def recipe_manager_register(request): # 本番デプロイ時
# def recipe_manager_register():          # 動作確認時
    url = request.args.get('url')

    res = requests.get(url)
    soup = BeautifulSoup(res.text, 'html.parser')
    title = soup.find(class_='recipe-title').get_text().replace('\n', '')
    img = soup.find(class_='photo large_photo_clickable')['src']
    ingredients = [
        re.sub('[^ぁ-ん ァ-ン ー-龥]', '', tag.get_text())
        for tag in soup.find(id='ingredients_list').find_all(class_='name')
    ]

    if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
        }

        return ('', 204, headers)

    headers = {
        'Access-Control-Allow-Origin': '*'
    }

    return ((json.dumps({
        'title': title,
        'img': img,
        'ingredients': ingredients,
    })), 200, headers)

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