from flask import Flask, request, jsonify

from main import ContentAnalyzer


app = Flask(__name__)

@app.route("/process-form", methods=["POST"])
def process_form():
    """
    API endpoint to process Google Form submissions.
    Expects JSON payload with: topic, receiverEmail, name, rowNumber
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({"status": "error", "message": "Invalid JSON payload"}), 400

        # Extract values from payload
        keyword = data.get("topic")
        receiver_email = data.get("receiverEmail")
        name = data.get("name")
        row_number = data.get("rowNumber")
        
        # You can also expand your form to include these instead of defaults
        industry = data.get("industry", "Fintech")
        location = data.get("location", "in")

        analyzer = ContentAnalyzer()

        # Run your analyzer logic here
        search_results = analyzer.search_google(keyword, industry, location)

        # (Optional) Generate content + save document
        # For now, just a sample dict
        content_data = {
            "title": f"{keyword.title()} in {location.upper()}?",
            "meta_description": f"Guide on {keyword} in {location.upper()}.",
            "content": f"Generated content about {keyword} for {industry} industry in {location.upper()}",
            "faq_section": [],
            "schema_markup": analyzer.generate_schema_markup("blog", {
                "title": f"{keyword.title()} in {location.upper()}?",
                "meta_description": f"Guide on {keyword} in {location.upper()}."
            })
        }

        analyzer.save_content(content_data, keyword, location, receiver_email)
        # Send email with the generated document (already handled inside save_content)
        # If you want to send separately, you can call:

        return jsonify({
            "status": "success",
            "message": f"Content generated for {keyword}",
            "rowNumber": row_number,
            "receiverEmail": receiver_email
        }), 200

    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500


if __name__ == "__main__":
    # If you run `python api-main.py`, it starts Flask instead of CLI input
    app.run(host="0.0.0.0", port=5009, debug=True)

