from __future__ import annotations

import re
from urllib.parse import urljoin


class PlaylistCleaner:
    def __init__(self, config: dict):
        self.config = config
        self.remove_discontinuity = bool(config.get("remove_discontinuity", True))
        self.convert_patterns = [re.compile(pattern) for pattern in config.get("rewrite_regex", [])]
        self.ad_patterns = config.get("ad_patterns", [])

    def clean(self, content: str, base_url: str) -> str:
        lines = content.splitlines()
        output: list[str] = []
        index = 0
        while index < len(lines):
            line = lines[index].rstrip()
            if self.remove_discontinuity and line == "#EXT-X-DISCONTINUITY":
                index += 1
                continue
            skip = self._matched_ad_pattern(lines, index)
            if skip:
                index += skip
                continue
            if line and not line.startswith("#"):
                line = self._absolute_url(line, base_url)
            output.append(line)
            index += 1
        return "\n".join(output).strip() + "\n"

    def _absolute_url(self, line: str, base_url: str) -> str:
        url = urljoin(base_url, line)
        for pattern in self.convert_patterns:
            url = pattern.sub("/", url)
        return url

    def _matched_ad_pattern(self, lines: list[str], start: int) -> int:
        for pattern in self.ad_patterns:
            if self._pattern_matches(lines, start, pattern):
                return len(pattern)
        return 0

    def _pattern_matches(self, lines: list[str], start: int, pattern: list[str]) -> bool:
        if start + len(pattern) > len(lines):
            return False
        for offset, expected in enumerate(pattern):
            current = lines[start + offset].strip()
            if expected == "ts":
                if not current.endswith(".ts"):
                    return False
            elif current != expected:
                return False
        return True

