from __future__ import annotations

from html import escape
from pathlib import Path

from .models import NormalizedMovie
from .utils import library_name, movie_folder_name


class NfoWriter:
    def __init__(self, root_dir: str, db_mount: str = "/strm"):
        self.root_dir = Path(root_dir)
        self.db_mount = db_mount.strip("/")

    def write(self, movie: NormalizedMovie) -> str:
        folder = self.root_dir / library_name(movie.media_type) / movie_folder_name(movie.title, movie.year, movie.tmdb_id)
        folder.mkdir(parents=True, exist_ok=True)
        tag = "movie" if movie.media_type == "movie" else "tvshow"
        path = folder / f"{tag}.nfo"
        path.write_text(self._content(movie, tag), encoding="utf-8")
        return str(path)

    def write_for_strm(self, movie: NormalizedMovie, strm_path: str) -> str:
        if movie.media_type != "movie":
            return self.write(movie)
        path = Path(strm_path)
        path.parent.mkdir(parents=True, exist_ok=True)
        nfo_path = path.with_suffix(".nfo")
        nfo_path.write_text(self._content(movie, "movie"), encoding="utf-8")
        return str(nfo_path)

    def write_for_db_strm(self, movie: NormalizedMovie, db_strm_path: str) -> str:
        prefix = f"/{self.db_mount}/"
        if not db_strm_path.startswith(prefix):
            return self.write(movie)
        relative = db_strm_path[len(prefix):]
        return self.write_for_strm(movie, self.root_dir / relative)

    def _content(self, movie: NormalizedMovie, tag: str) -> str:
        lines = [
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
            f"<{tag}>",
            f"  <title>{escape(movie.title)}</title>",
            f"  <originaltitle>{escape(movie.original_title)}</originaltitle>",
            f"  <plot>{escape(movie.content)}</plot>",
            f"  <year>{escape(movie.year)}</year>",
            f"  <runtime>{escape(movie.runtime)}</runtime>",
            f"  <thumb>{escape(movie.poster_url)}</thumb>",
            f"  <fanart>{escape(movie.backdrop_url)}</fanart>",
            f"  <imdbid>{escape(movie.imdb_id)}</imdbid>",
            f"  <tmdbid>{escape(movie.tmdb_id)}</tmdbid>",
        ]
        for genre in movie.genres:
            lines.append(f"  <genre>{escape(genre)}</genre>")
        for country in movie.countries:
            lines.append(f"  <country>{escape(country)}</country>")
        for actor in movie.actors:
            lines.append(f"  <actor><name>{escape(actor)}</name></actor>")
        for director in movie.directors:
            lines.append(f"  <director>{escape(director)}</director>")
        lines.append(f"</{tag}>")
        return "\n".join(lines) + "\n"
