import requests
from bs4 import BeautifulSoup
import json
import re
from flask import Flask, jsonify

app = Flask(__name__)

def fetch_cfs():
    url = "https://www.americanwhitewater.org/content/gauge/detail-new/4439"
    
    try:
        # Fetch the webpage content
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for bad status codes
        
        # Parse the HTML content
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # Search for CFS value in the entire page content
        cfs_pattern = r'(\d+(?:\.\d+)?)\s*cfs'
        match = re.search(cfs_pattern, soup.get_text())
        
        if match:
            cfs_value = match.group(1)
            return {"Value": cfs_value}
        
        # If CFS not found, return debug information
        tables = soup.find_all('table')
        
        debug_info = {
            "Tables_found": len(tables),
            "Table_contents": [table.get_text(strip=True) for table in tables],
            "Page_title": soup.title.string if soup.title else "No title found",
            "Text_snippet": soup.get_text()[:1000]  # First 1000 characters of the page text
        }
        
        return {
            "Error": "CFS value not found",
            "Debug": debug_info
        }
    
    except requests.RequestException as e:
        return {"Error": f"Failed to fetch data: {str(e)}"}
    except Exception as e:
        return {
            "Error": f"An unexpected error occurred: {str(e)}",
            "Debug": {
                "Error_type": type(e).__name__,
                "Error_args": str(e.args)
            }
        }

@app.route('/cfs', methods=['GET'])
def get_cfs():
    result = fetch_cfs()
    return jsonify(result)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8081)