import logging
import re
import subprocess
from datetime import datetime
from pathlib import Path
from typing import List, Optional

import requests
from bs4 import BeautifulSoup
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, relationship, mapped_column

from src.db.models.base import Base, BaseMixin, BaseVideoMixin


class MediaFile(Base, BaseMixin, BaseVideoMixin):
    """
    MediaFile represents video link.
    """

    __tablename__ = "media_file"
    media_actor_files: Mapped[List["MediaActorFile"]] = relationship(
        back_populates="media_file"
    )

    def __repr__(self):
        return f"MediaFile({self.id} {self.title} {self.title})"

    def __str__(self):
        return f"{self.title}({self.id})"

    def update_title(self):
        """
        Update title from url.
        """


class MediaActor(Base, BaseMixin):
    __tablename__ = "media_actor"
    name: Mapped[str]
    url: Mapped[Optional[str]] = mapped_column(unique=True)
    media_actor_files = relationship("MediaActorFile")

    def __repr__(self) -> str:
        return f"MediaActor({self.id} {self.name} {self.url})"

    def __str__(self) -> str:
        return f"{self.url}({self.id})"


class MediaActorFile(Base, BaseMixin):
    __tablename__ = "media_actor_file"
    media_actor_id: Mapped[str] = mapped_column(
        ForeignKey("media_actor.id"), nullable=False
    )
    media_actor: Mapped[MediaActor] = relationship(back_populates="media_actor_files")
    media_file_id: Mapped[str] = mapped_column(
        ForeignKey("media_file.id"), nullable=True
    )
    media_file: Mapped[MediaFile] = relationship(back_populates="media_actor_files")

    def __repr__(self):
        return f"MediaActorFile({self.id} {self.media_actor_id} {self.media_file_id})"

    def __str__(self) -> str:
        return f"{self.id} {self.media_actor_id} {self.media_file_id}"


class MediaArticle(Base, BaseMixin):
    __tablename__ = "media_article"
    review: Mapped[bool]
    title: Mapped[str]
    url: Mapped[str] = mapped_column(unique=True)


class MediaVideo(Base, BaseMixin):
    """
    MediaFile represents video link.
    """

    __tablename__ = "media_video"
    cloud_link: Mapped[str]
    file_name: Mapped[str]
    path: Mapped[str]
    review: Mapped[bool]
    title: Mapped[str]
    url: Mapped[str] = mapped_column(unique=True)
    should_download: Mapped[bool]

    def __repr__(self):
        return f"MediaFile({self.id} {self.title} {self.url})"

    def __str__(self):
        if self.title is None:
            return f"{self.url}({self.id})"
        else:
            return f"{self.title}({self.id})"
