"""
Issue CLI commands.
"""

from typing import List, Optional, Any

from tddai import TddaiError
from services import IssueService
from cli.presenters import OutputFormatter, IssueView


class IssueCommands:
    """Commands for issue operations."""

    def __init__(self) -> None:
        self.service = IssueService()

    def list_issues(self) -> None:
        """List all issues."""
        try:
            issues = self.service.list_issues()
            IssueView.show_list(issues)
        except TddaiError as e:
            OutputFormatter.exit_with_error(str(e))

    def list_open_issues(self) -> None:
        """List only open issues."""
        try:
            issues = self.service.list_open_issues()
            IssueView.show_open_issues(issues)
        except TddaiError as e:
            OutputFormatter.exit_with_error(str(e))

    def show_issue(self, issue_number: int) -> None:
        """Show detailed issue information."""
        try:
            issue_data = self.service.get_issue_details(issue_number)
            IssueView.show_issue_details(issue_data)
        except TddaiError as e:
            OutputFormatter.exit_with_error(str(e))

    def create_issue(self, title: str, body: str, issue_type: str = "enhancement") -> None:
        """Create a new issue."""
        try:
            OutputFormatter.info(f"Creating {issue_type} issue: {title}")
            OutputFormatter.empty_line()

            result = self.service.create_issue(title, body, labels=[issue_type])
            IssueView.show_creation_success(result, issue_type)

        except TddaiError as e:
            OutputFormatter.exit_with_error(f"Error creating issue: {e}")

    def create_enhancement_issue(self, title: str, use_case: str,
                               technical_requirements: str = "",
                               acceptance_criteria: Optional[List[str]] = None,
                               dependencies: Optional[List[str]] = None,
                               priority: str = "Medium") -> None:
        """Create a structured enhancement issue."""
        try:
            OutputFormatter.info(f"Creating enhancement issue: {title}")
            OutputFormatter.empty_line()

            result = self.service.create_enhancement_issue(
                title, use_case, technical_requirements,
                acceptance_criteria, dependencies, priority
            )

            OutputFormatter.success("Enhancement issue created successfully!")
            OutputFormatter.key_value("Number", f"#{result['number']}")
            OutputFormatter.key_value("Title", result['title'])
            OutputFormatter.key_value("Priority", priority)

            if 'html_url' in result:
                OutputFormatter.key_value("URL", result['html_url'])

            OutputFormatter.empty_line()
            print("💡 Next steps:")
            print(f"   - Use 'make tdd-start NUM={result['number']}' to begin work")
            print(f"   - Use 'make show-issue NUM={result['number']}' to view details")

        except TddaiError as e:
            OutputFormatter.exit_with_error(f"Error creating enhancement issue: {e}")

    def create_from_template(self, template_file: str, **kwargs: Any) -> None:
        """Create issue from template file."""
        try:
            OutputFormatter.info(f"Creating issue from template: {template_file}")
            OutputFormatter.empty_line()

            result = self.service.create_from_template(template_file, **kwargs)

            OutputFormatter.success("Issue created from template successfully!")
            OutputFormatter.key_value("Number", f"#{result['number']}")
            OutputFormatter.key_value("Title", result['title'])

            if 'html_url' in result:
                OutputFormatter.key_value("URL", result['html_url'])

            OutputFormatter.empty_line()
            print("💡 Next steps:")
            print(f"   - Use 'make tdd-start NUM={result['number']}' to begin work")
            print(f"   - Use 'make show-issue NUM={result['number']}' to view details")

        except TddaiError as e:
            OutputFormatter.exit_with_error(f"Error creating issue from template: {e}")

    def close_issue(self, issue_number: int, comment: str = "") -> None:
        """Close an issue with optional comment."""
        try:
            OutputFormatter.info(f"Closing issue #{issue_number}")
            if comment:
                OutputFormatter.info(f"Comment: {comment}")
            OutputFormatter.empty_line()

            result = self.service.close_issue(issue_number, comment)

            OutputFormatter.success(f"Issue #{issue_number} closed successfully!")
            OutputFormatter.key_value("Title", result['title'])
            OutputFormatter.key_value("State", result['state'])

            if 'html_url' in result:
                OutputFormatter.key_value("URL", result['html_url'])

        except TddaiError as e:
            OutputFormatter.exit_with_error(f"Error closing issue: {e}")

    def analyze_coverage(self, issue_number: int) -> None:
        """Analyze test coverage for a specific issue."""
        try:
            coverage_data = self.service.analyze_coverage(issue_number)
            IssueView.show_coverage_analysis(coverage_data)
        except TddaiError as e:
            OutputFormatter.exit_with_error(str(e))