#!/usr/bin/python3
import requests
from bs4 import BeautifulSoup
import MySQLdb
from datetime import date, datetime

# ------------------------------
# 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"

LOG_FILE = "/var/log/rlp_nav.log"


# ------------------------------
# SIMPLE LOGGER
# ------------------------------
def log(msg: str):
    with open(LOG_FILE, "a") as f:
        f.write(f"{datetime.now()} - {msg}\n")


# ------------------------------
# FETCH PAGE
# ------------------------------
try:
    resp = requests.get(URL, headers={"User-Agent": "Mozilla/5.0"}, timeout=20)
    resp.raise_for_status()
except Exception as e:
    log(f"ERROR fetching page: {e}")
    raise SystemExit("Fetch failed")

soup = BeautifulSoup(resp.text, "html.parser")


# ------------------------------
# SAFE SELECTOR
# ------------------------------
def safe_select(selector):
    el = soup.select_one(selector)
    return el.get_text(strip=True) if el else None


# Extract NAV (main FT value)
price_text = safe_select(
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(1) .mod-ui-data-list__value"
)
today_change = safe_select(
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(2) .mod-format--pos"
) or safe_select(
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(2) .mod-format--neg"
)
year_change = safe_select(
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(3) .mod-format--pos"
) or safe_select(
    "ul.mod-tearsheet-overview__quote__bar > li:nth-child(3) .mod-format--neg"
)

if not price_text:
    log("ERROR: Failed to extract NAV price")
    raise SystemExit("Could not extract NAV price")

try:
    nav_price = float(price_text)
except ValueError:
    log(f"ERROR converting price: '{price_text}'")
    raise SystemExit("Invalid price format")


# ------------------------------
# WRITE TO DATABASE
# ------------------------------
try:
    conn = MySQLdb.connect(
        host=DB_HOST,
        user=DB_USER,
        passwd=DB_PASS,
        db=DB_NAME,
        charset="utf8mb4"
    )
    cur = conn.cursor()
except Exception as e:
    log(f"DB connection error: {e}")
    raise SystemExit("Database connection failed")


sql = """
    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)
"""

cur.execute(sql, (date.today(), nav_price, today_change, year_change))
conn.commit()
conn.close()

log(f"SAVED NAV: {nav_price} | Change: {today_change} | YR: {year_change}")
print("Saved NAV:", nav_price)
