#!/usr/bin/env python3
import os
import shlex
from typing import Sequence
from classes.user import User
from functions import LOG
from functions import load_config_variables
from functions import run


class Gallery:
    def __init__(self) -> None:
        self.archive: bool = True
        self.skip_arg: str = ""
        self.link: str = ""
        self.dest: str = ""
        self.list: str = ""
        self.opt_args: str | Sequence[str] = ""
        self.command: list[str] = []

    def generate_command(self, user: User | None = None, is_comic: bool = False) -> None:
        """Generates a command string."""
        if user is None:
            user = User(1)
        if is_comic:
            configs = load_config_variables()
            directory = str(configs["comic"]["download-dir"])
            database = str(configs["comic"]["database"])
            queue = str(configs["comic"][f"{self.list}-list"]) if self.list else ""
        else:
            directory = str(user.directories[self.dest])
            database = str(user.dbs["gallery"])
            queue = str(user.lists[self.list]) if self.list else ""

        command = ["gallery-dl", "--sleep", str(user.sleep)]
        if self.skip_arg:
            command += shlex.split(self.skip_arg)
        if self.dest or is_comic:
            command += ["--dest", directory]
        if self.archive:
            command += ["--download-archive", database]
        if self.opt_args:
            if isinstance(self.opt_args, str):
                command += shlex.split(self.opt_args)
            else:
                command += list(self.opt_args)

        # Add authentication options from environment variables
        auth_env = {
            "extractor.pixiv.refresh-token": "GALLERY_DL_PIXIV_REFRESH_TOKEN",
            "extractor.bluesky.password": "GALLERY_DL_BLUESKY_PASSWORD",
            "extractor.deviantart.refresh-token": "GALLERY_DL_DEVIANTART_REFRESH_TOKEN",
            "extractor.flickr.access-token": "GALLERY_DL_FLICKR_ACCESS_TOKEN",
            "extractor.flickr.access-token-secret": "GALLERY_DL_FLICKR_ACCESS_TOKEN_SECRET",
            "extractor.reddit.refresh-token": "GALLERY_DL_REDDIT_REFRESH_TOKEN",
            "extractor.tumblr.access-token": "GALLERY_DL_TUMBLR_ACCESS_TOKEN",
            "extractor.tumblr.access-token-secret": "GALLERY_DL_TUMBLR_ACCESS_TOKEN_SECRET",
            "extractor.tumblr.api-key": "GALLERY_DL_TUMBLR_API_KEY",
            "extractor.tumblr.api-secret": "GALLERY_DL_TUMBLR_API_SECRET",
        }
        for key, env_var in auth_env.items():
            command += ["-o", f"{key}={os.environ.get(env_var, '')}"]

        if self.link and not self.list:
            command.append(self.link)
        if self.list and not self.link:
            command += ["-i", queue]

        LOG.debug(command)
        self.command = command

    def run_command(self, verbose: bool):
        run(self.command, verbose)
