#!/usr/bin/env python3
"""Collect every book's title, price, rating and stock from books.toscrape.com
(a practice site built for scraping) into a CSV. No extra packages needed.

    python3 scrape_books.py                     # all 50 pages -> books.csv
    python3 scrape_books.py --pages 2 -o few.csv
"""
import argparse
import csv
import time
import urllib.request
from html.parser import HTMLParser
from urllib.parse import urljoin

START = "https://books.toscrape.com/catalogue/page-1.html"
RATINGS = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}


class ListPage(HTMLParser):
    """Pulls the book cards and the 'next' link out of one listing page."""

    def __init__(self):
        super().__init__()
        self.books, self.next, self._book, self._in = [], None, None, None

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        cls = a.get("class", "")
        if tag == "article" and "product_pod" in cls:
            self._book = {"title": "", "price": "", "rating": 0, "in_stock": False, "url": ""}
        elif self._book is not None:
            if tag == "p" and "star-rating" in cls:
                self._book["rating"] = RATINGS.get(cls.split()[-1], 0)
            elif tag == "a" and a.get("title"):
                self._book["title"], self._book["url"] = a["title"], a.get("href", "")
            elif tag == "p" and "price_color" in cls:
                self._in = "price"
            elif tag == "p" and "instock" in cls:
                self._in = "stock"
        if tag == "li" and cls == "next":
            self._in = "next"
        elif tag == "a" and self._in == "next":
            self.next, self._in = a.get("href"), None

    def handle_data(self, data):
        if self._book is None:
            return
        if self._in == "price":
            self._book["price"] = float(data.strip().lstrip("Â£"))
            self._in = None
        elif self._in == "stock" and data.strip():
            self._book["in_stock"] = "In stock" in data
            self._in = None

    def handle_endtag(self, tag):
        if tag == "article" and self._book is not None:
            self.books.append(self._book)
            self._book = None


def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent": "portfolio-sample-scraper"})
    with urllib.request.urlopen(req, timeout=20) as r:
        return r.read().decode("utf-8")


def scrape(start=START, pages=None, get=fetch, delay=0.5):
    url, out, n = start, [], 0
    while url and (pages is None or n < pages):
        page = ListPage()
        page.feed(get(url))
        for b in page.books:
            b["url"] = urljoin(url, b["url"])
        out += page.books
        n += 1
        url = urljoin(url, page.next) if page.next else None
        if url and delay:
            time.sleep(delay)  # be polite to the site
    return out


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--pages", type=int, help="stop after this many pages")
    ap.add_argument("-o", "--output", default="books.csv")
    a = ap.parse_args(argv)
    books = scrape(pages=a.pages)
    with open(a.output, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=["title", "price", "rating", "in_stock", "url"])
        w.writeheader()
        w.writerows(books)
    print(f"Saved {len(books)} books to {a.output}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
