import requests
from bs4 import BeautifulSoup
import mysql.connector
from datetime import date

# ---- CONFIG ----
URL = "https://markets.ft.com/data/funds/tearsheet/summary?s=GB00BMXYXW53:GBP"

DB_HOST = "192.168.0.41"
DB_USER = "mawdz09"
DB_PASS = "asaxPI1324"
DB_NAME = "RLPFund"

# ---- FETCH HTML ----
resp = requests.get(URL, headers={"User-Agent": "Mozilla/5.0"})
html = resp.text
soup = BeautifulSoup(html, "html.parser")

# ---- EXTRACT UI VALUES (rounded by FT) ----
price_text = soup.select_one(
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(1) .mod-ui-data-list__value"
).get_text(strip=True)

today_change = soup.select_one(
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(2) .mod-format--pos, "
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(2) .mod-format--neg"
).get_text(strip=True)

year_change = soup.select_one(
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(3) .mod-format--pos, "
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(3) .mod-format--neg"
).get_text(strip=True)

# Parse the decimal change
delta_raw = today_change.split("/")[0].strip()   # "0.007"
delta_value = float(delta_raw)

# ---- SAVE TO DATABASE ----
conn = mysql.connector.connect(
    host=DB_HOST, user=DB_USER, password=DB_PASS, database=DB_NAME
)
cur = conn.cursor()

# Get yesterday’s price (full precision)
cur.execute("SELECT price FROM nav_prices ORDER BY price_date DESC LIMIT 1")
row = cur.fetchone()

if row:
    prev_price = float(row[0])
    real_price = round(prev_price + delta_value, 4)
else:
    # First run
    real_price = float(price_text)

# Insert real precise NAV
cur.execute("""
    INSERT INTO nav_prices (price_date, price, change_text, year_change)
    VALUES (%s, %s, %s, %s)
    ON DUPLICATE KEY UPDATE price = VALUES(price),
                          change_text = VALUES(change_text),
                          year_change = VALUES(year_change)
""", (date.today(), real_price, today_change, year_change))

conn.commit()
conn.close()

print("Saved NAV:", real_price, today_change, year_change)
