"""Weather site preset."""
from urllib.parse import urlparse


class Weather:
    def __init__(self, client):
        self.client = client

    def extract(self, url):
        try:
            location = urlparse(url).path.strip("/").split("/")[0] or "London"
            resp = self.client.fetch(f"https://wttr.in/{location}?format=j1", timeout=10)
            if resp.status_code == 200:
                d = resp.json()
                cur = d.get("current_condition", [{}])[0]
                area = d.get("nearest_area", [{}])[0]
                loc_name = (area.get("areaName", [{}])[0].get("value", location))
                return {"success": True, "data": {
                    "location": loc_name,
                    "temp_c": cur.get("temp_C"),
                    "description": cur.get("weatherDesc", [{}])[0].get("value"),
                    "humidity": cur.get("humidity"),
                    "wind": cur.get("windspeedKmph"),
                }, "source": "wttr.in", "error": None}
            return {"success": False, "data": {}, "source": "wttr.in", "error": f"HTTP {resp.status_code}"}
        except Exception as e:
            return {"success": False, "data": {}, "source": "wttr.in", "error": str(e)}
