import copy

from page_scraper.entities.models import PageContext
from page_scraper.links.utils import prepare_links, get_page_canonical_url
from page_scraper.core.utils import canonical_domain


class CanonicalScraper:
    def run(self,page:PageContext) -> PageContext:
        soup_copy = copy.copy(page.soup)

        url = get_page_canonical_url(soup_copy)

        if not url:
            return page

        domain = canonical_domain(page.url)
        result = prepare_links(domain, [url],"canonical")
        page.canonical_url = result[0]
        page.links.extend(result)

        return page