"""MCP tool implementation for view_history.

Provides the main tool logic for generating a self-contained HTML
history viewer and opening it in the browser.
"""

import webbrowser
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional

from tools.history.reader import HistoryReader
from tools.view_history.html_generator import HistoryHtmlGenerator
from tools.view_history.utils import get_project_name


@dataclass
class ViewHistoryResponse:
    """Response from the view_history tool."""

    success: bool
    html_path: Optional[str] = None
    audit_count: int = 0
    message: str = ""
    browser_opened: bool = False
    error: Optional[str] = None

    def to_dict(self) -> dict[str, Any]:
        result = {
            "success": self.success,
            "audit_count": self.audit_count,
            "message": self.message,
            "browser_opened": self.browser_opened,
        }
        if self.html_path:
            result["html_path"] = self.html_path
        if self.error:
            result["error"] = self.error
        return result


class ViewHistoryTool:
    """MCP tool for viewing audit history in browser."""

    @property
    def name(self) -> str:
        return "view_history"

    @property
    def description(self) -> str:
        return (
            "Generate and open a self-contained HTML viewer for audit history. "
            "Creates .optix/history_viewer.html and opens it in the default browser."
        )

    def execute(self, project_path: Optional[str] = None) -> ViewHistoryResponse:
        """Execute the view history tool.

        Args:
            project_path: Optional path to project root. Defaults to cwd.

        Returns:
            ViewHistoryResponse with result
        """
        try:
            project_root = Path(project_path) if project_path else Path.cwd()
            if not project_root.exists():
                return ViewHistoryResponse(
                    success=False,
                    error=f"Project path does not exist: {project_root}",
                    message=f"Project path does not exist: {project_root}",
                )

            html_path = project_root / ".optix" / "history_viewer.html"

            if not html_path.exists():
                self._generate_html(project_root, html_path)

            history_dir = project_root / ".optix" / "history"
            reader = HistoryReader(history_dir)
            audit_count = len(reader.list_audits())

            browser_opened = False
            try:
                file_url = f"file://{html_path.resolve()}"
                webbrowser.open(file_url)
                browser_opened = True
            except Exception:
                pass

            return ViewHistoryResponse(
                success=True,
                html_path=str(html_path),
                audit_count=audit_count,
                message=f"History viewer opened with {audit_count} audits",
                browser_opened=browser_opened,
            )

        except PermissionError as e:
            return ViewHistoryResponse(
                success=False,
                error=f"Permission denied: {e}",
                message="Permission denied writing to .optix directory",
            )

        except OSError as e:
            return ViewHistoryResponse(
                success=False,
                error=f"File system error: {e}",
                message=f"File system error: {e}",
            )

        except Exception as e:
            return ViewHistoryResponse(
                success=False,
                error=f"Unexpected error: {e}",
                message=f"Unexpected error: {e}",
            )

    def _generate_html(self, project_root: Path, html_path: Path) -> None:
        """Generate HTML file from audit history."""
        project_name = get_project_name(project_root) or project_root.name
        history_dir = project_root / ".optix" / "history"
        reader = HistoryReader(history_dir)

        summaries = reader.list_audits()
        audits_with_findings = []
        for summary in summaries:
            full_audit = reader.get_audit(summary.dir_name)
            if full_audit:
                audits_with_findings.append(full_audit)
            else:
                audits_with_findings.append(summary.to_dict())

        generator = HistoryHtmlGenerator(project_name, audits_with_findings)
        html_path.parent.mkdir(parents=True, exist_ok=True)
        html_path.write_text(generator.generate(), encoding="utf-8")

