"""
Copyright (C) 2024-2026 Mo Zhou <lumin@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

import difflib
import os
import pty
import re
import select
import shlex
import subprocess
import tempfile
from collections import deque

from rich.console import Console
from rich.live import Live
from rich.panel import Panel
from rich.text import Text

from .base import Tool, _diff_stat, _short, render_diff


class DgetRunner(Tool):
    """Tool to download Debian source/binary packages with dget."""

    name = "dget_runner"
    description = (
        "Download Debian packages with dget (devscripts). Given a .dsc or "
        ".changes URL, downloads all referenced files and, by default, unpacks "
        "the source. Given a plain package name, fetches its current source "
        "from the archive. Downloads files into the working directory and "
        "accesses the network, so it requires user confirmation."
    )

    def needs_confirmation(self, args_dict: dict) -> tuple:
        target = args_dict.get("target", "")
        return True, f"Download package with dget: {target}"

    def confirmation_context(self, args_dict: dict) -> str:
        cmd = self._build_cmd(args_dict)
        return "Command to run:\n" + " ".join(shlex.quote(c) for c in cmd)

    def _build_cmd(self, args_dict: dict) -> list:
        cmd = ["dget", "-q"]
        if args_dict.get("download_only"):
            cmd.append("-d")
        if args_dict.get("extra_args"):
            cmd.extend(shlex.split(args_dict["extra_args"]))
        cmd.append(args_dict.get("target", ""))
        return cmd

    def summary(self, args_dict: dict) -> str:
        return f"dget {_short(args_dict.get('target', ''), 60)}"

    def __call__(
        self,
        target: str,
        download_only: bool = False,
        path: str = ".",
        extra_args: str = None,
    ) -> str:
        try:
            if not target or not target.strip():
                return "Error: 'target' must not be empty."

            cwd = os.path.expanduser(path)
            if not os.path.isdir(cwd):
                return f"Error: '{cwd}' does not exist."

            args_dict = {
                "target": target,
                "download_only": download_only,
                "extra_args": extra_args,
            }
            cmd = self._build_cmd(args_dict)

            try:
                result = subprocess.run(
                    cmd,
                    env={**os.environ, "LC_ALL": "C"},
                    cwd=cwd,
                    capture_output=True,
                    text=True,
                    timeout=600,
                )
            except FileNotFoundError:
                return "Error: 'dget' is not installed (package: devscripts)."
            except subprocess.TimeoutExpired:
                return "Error: dget timed out after 600s."

            out = result.stdout
            if result.stderr:
                out += "\nSTDERR:\n" + result.stderr
            if len(out) > 4000:
                out = out[:2000] + "\n...(truncated output)...\n" + out[-2000:]

            ret = f"Status: {result.returncode}\n"
            ret += f"Output:\n{out}\n" if out.strip() else "No output.\n"
            return ret
        except Exception as e:
            return f"Error: {str(e)}"

    parameters = {
        "type": "object",
        "properties": {
            "target": {
                "type": "string",
                "description": "A .dsc/.changes URL, a bare package name, or any "
                "URL to fetch.",
            },
            "download_only": {
                "type": "boolean",
                "description": "If true, download files without unpacking the "
                "source (dget -d).",
            },
            "path": {
                "type": "string",
                "description": "Directory to download into. Defaults to '.'.",
            },
            "extra_args": {
                "type": "string",
                "description": "Additional arguments passed directly to dget.",
            },
        },
        "required": ["target"],
    }
