import tempfile
from urllib.parse import parse_qs, urlparse
from flask import Flask, render_template, request, redirect, send_file, url_for, jsonify
from youtube_transcript_api import YouTubeTranscriptApi
from models import db, Item
from datetime import datetime as dt
import requests, csv, json

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///items.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

@app.before_request
def initialize_app():
    if not hasattr(app, 'is_initialized'):
        db.create_all()
        app.is_initialized = True


@app.route('/')
def home():
    items = Item.query.all()
    testList = [1,2,3,"Apple"]
    username = "Test_Username" 
    return render_template('home.html', items=items, testList=testList, username=username)

@app.route('/relative-rank-ai')
def rank_ai():
    return render_template('relative_rank_ai.html')

@app.route('/relative-rank')
def rank():
    return render_template('relative_rank.html')

@app.route("/save-rankings", methods=["POST"])
def save_rankings():
    data = request.json  # Get the ranked items and tiers
    print(data)  # For debugging, print the data received
    return jsonify({"message": "Rankings saved successfully!"})

@app.route('/add', methods=['GET', 'POST'])
def add_item():
    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        new_item = Item(name=name, description=description)
        db.session.add(new_item)
        db.session.commit()
        return redirect(url_for('home'))
    return render_template('add_item.html')

@app.route('/motion')
def motion():
    return render_template('motion.html')

@app.route('/about')
def about():
    return render_template('about.html', now=dt.now())

@app.route('/short_stories/')
@app.route('/short_stories/<int:story>')
def short_stories(story=1):
    with open("./static/stories.json", "r") as f:
        stories = json.load(f)
    return render_template('short_stories.html',stories=stories, story=story )

@app.route('/weather')
def get_weather():
    # Replace with your API's URL
    api_url = "https://api.open-meteo.com/v1/forecast?latitude=32.681676709461826&longitude=-97.373412014933&current_weather=true"
    
    try:
        # Make the GET request to the API
        response = requests.get(api_url)
        
        # Check if the request was successful
        response.raise_for_status()  # Raises an HTTPError for bad responses
        
        # Parse the JSON response
        weather_data = response.json()
        
        # Extract relevant information
        units = weather_data.get('current_weather_units', {})
        current_weather = weather_data.get('current_weather', {})
        temperature = current_weather.get('temperature', 'N/A')
        temperature_unit = units.get('temperature', "")
        wind_speed = current_weather.get('windspeed', 'N/A')
        wind_speed_unit = units.get('windspeed', "")
        wind_direction = current_weather.get('winddirection', 'N/A')
        wind_direction_unit = units.get('winddirection', "")
        # Pass the data to the template
        return render_template('weather.html', temperature=temperature, wind_speed=wind_speed, temperature_unit=temperature_unit, wind_speed_unit=wind_speed_unit, wind_direction=wind_direction,wind_direction_unit=wind_direction_unit )
    
    except requests.exceptions.RequestException as e:
        # Handle errors
        return f"An error occurred: {e}"

def load_vocab(csv_filename):
    vocab_list = []
    with open(csv_filename, newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            hiragana_katakana, kanji, english = row
            japanese = kanji if kanji else hiragana_katakana  # Use kanji if available, otherwise use kana
            vocab_list.append((japanese, english))
    return vocab_list

@app.route('/vocabulary')
def vocabulary():
    vocab_list = load_vocab('static/vocab.csv')  # Ensure your CSV is in the 'static' folder
    return render_template('vocabulary.html', vocab_list=vocab_list)


@app.route('/percent-change-calculator',methods=['GET','POST'])
def pcc():
    if request.method == 'POST':
        value_chain = []
        starting = float(request.form['starting-value'])
        drop = float(request.form['drop'])
        praise = float(request.form['raise'])
        dropped_value = starting - (starting * drop/100)
        new_value = dropped_value + dropped_value * praise/100
        percent_to_normal = starting/dropped_value * 100
        value_chain.append(starting)
        value_chain.append(dropped_value)
        value_chain.append(new_value)
        value_chain.append(percent_to_normal)
        print(value_chain)
        return render_template('pcc.html', value = value_chain)
    return render_template('pcc.html')

def get_video_id(url: str) -> str:
    """Extract YouTube video ID from URL."""
    query = urlparse(url)
    if query.hostname in ['www.youtube.com', 'youtube.com']:
        return parse_qs(query.query)['v'][0]
    elif query.hostname == 'youtu.be':
        return query.path[1:]
    else:
        raise ValueError("Invalid YouTube URL")

def fetch_transcript(url: str, language: str = 'ja') -> str:
    """Fetch transcript text."""
    video_id = get_video_id(url)
    ytt_api = YouTubeTranscriptApi()
    transcript = ytt_api.fetch(video_id, languages=[language])
    return (" ".join([entry.text for entry in transcript]),transcript.video_id)

@app.route("/transcript", methods=["GET", "POST"])
def transcript():
    if request.method == "POST":
        yt_url = request.form["url"]
        lang = request.form.get("lang", "ja")
        try:
            transcript, video_id = fetch_transcript(yt_url, lang)
        except Exception as e:
            return f"Error: {e}", 400

        # Save to a temporary file and return immediately
        tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8")
        tmp.write(transcript)
        tmp.close()
        return send_file(tmp.name, as_attachment=True, download_name=f"{video_id}-transcript.txt")

    return render_template("transcript.html")

@app.route("/nationalparks")
def nationalparks():
    return render_template("nationalparks.html")

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8000)
