"""
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 LintianRunner(Tool):
    """Tool to run lintian on a Debian package."""

    name = "lintian_runner"
    description = (
        "Run lintian, a static analysis tool for Debian packages, "
        "to dissect packages and report bugs and policy violations. "
        "By default it checks the package in the current directory."
    )

    def summary(self, args_dict: dict) -> str:
        return f"lintian {args_dict.get('path', '.')}"

    def __call__(
        self,
        path: str = ".",
        info: bool = False,
        display_info: bool = False,
        pedantic: bool = False,
        extra_args: str = None,
    ) -> str:
        try:
            path = os.path.expanduser(path)
            if not os.path.exists(path):
                return f"Error: '{path}' does not exist."

            cmd = ["lintian"]
            if info:
                cmd.append("-i")
            if display_info:
                cmd.append("-I")
            if pedantic:
                cmd.append("--pedantic")

            if extra_args:
                cmd.extend(shlex.split(extra_args))

            cmd.append(path)

            console = Console()
            with console.status(f"Running lintian on {path}..."):
                result = subprocess.run(cmd, capture_output=True, text=True)

            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"
            if out.strip():
                ret += f"Output:\n{out}\n"
            else:
                ret += "No output (no issues found).\n"
            return ret
        except Exception as e:
            return f"Error: {str(e)}"

    parameters = {
        "type": "object",
        "properties": {
            "path": {
                "type": "string",
                "description": "Path to the .changes, .deb, .dsc file or package source directory. Defaults to '.'.",
            },
            "info": {
                "type": "boolean",
                "description": "If true, print explanatory information about each problem (lintian -i).",
            },
            "display_info": {
                "type": "boolean",
                "description": "If true, display informational tags (lintian -I).",
            },
            "pedantic": {
                "type": "boolean",
                "description": "If true, display pedantic tags (lintian --pedantic).",
            },
            "extra_args": {
                "type": "string",
                "description": "Additional arguments passed directly to lintian.",
            },
        },
        "required": [],
    }
