"""
Post-validation share trigger.

Captures the 5-second window after grade reveal when users are most
likely to share. This is the single highest-leverage feature for
viral growth.
"""

import contextlib
import time
import webbrowser

import click

from deepsweep.constants import SYMBOL_PASS

from .badge import generate_badge_markdown
from .social import get_linkedin_url, get_share_text_for_grade, get_twitter_url


def _copy_to_clipboard(text: str) -> bool:
    """Copy text to clipboard (cross-platform, no external deps)."""
    import subprocess

    try:
        if (
            subprocess.run(
                ["which", "pbcopy"],
                capture_output=True,
                check=False,
            ).returncode
            == 0
        ):
            subprocess.run(
                ["pbcopy"],
                input=text.encode(),
                check=True,
                capture_output=True,
            )
            return True

        if (
            subprocess.run(
                ["which", "xclip"],
                capture_output=True,
                check=False,
            ).returncode
            == 0
        ):
            subprocess.run(
                ["xclip", "-selection", "clipboard"],
                input=text.encode(),
                check=True,
                capture_output=True,
            )
            return True

        if (
            subprocess.run(
                ["which", "xsel"],
                capture_output=True,
                check=False,
            ).returncode
            == 0
        ):
            subprocess.run(
                ["xsel", "--clipboard", "--input"],
                input=text.encode(),
                check=True,
                capture_output=True,
            )
            return True

    except (subprocess.CalledProcessError, OSError):
        pass

    return False


def show_share_trigger(
    grade: str,
    score: int,
    passed_count: int,
    total_count: int,
    project_name: str = "my-project",
    skip_delay: bool = False,
) -> str | None:
    """
    Show share prompt after validation completes.

    Displays a brief interactive prompt allowing the user to copy a
    README badge, share on social media, or skip.

    Args:
        grade: Letter grade (A, B, C, D, F).
        score: Numeric score 0-100.
        passed_count: Number of checks that passed.
        total_count: Total number of checks run.
        project_name: Name of the project being validated.
        skip_delay: If True, skip the brief pause before showing.

    Returns:
        Action taken as a string, or None if skipped.
    """
    # Brief pause to let the grade sink in
    if not skip_delay:
        time.sleep(1.5)

    # Track that the share prompt was shown
    with contextlib.suppress(Exception):
        from deepsweep.reputation.metrics import track_share_prompt

        track_share_prompt(score=score, tier="", context="post_validation")

    headline = _get_share_headline(grade)
    subline = f"Your code passed {passed_count} of {total_count} security checks"

    border_color = "green" if grade.startswith("A") else "blue"

    click.echo()
    click.echo(click.style(f"--- Grade {grade} ---", fg=border_color, bold=True))
    click.echo()
    click.echo(click.style(f"  {headline}", bold=True))
    click.echo(f"  {subline}")
    click.echo()
    click.echo("  Share your security grade:")
    click.echo()
    click.echo("    [1] Copy badge for README")
    click.echo("    [2] Share on X (Twitter)")
    click.echo("    [3] Share on LinkedIn")
    click.echo("    [4] Copy share link")
    click.echo()
    click.echo(click.style("  Press Enter to skip", dim=True))
    click.echo()

    try:
        choice = click.prompt(
            "Your choice",
            default="",
            show_default=False,
        )
    except (EOFError, KeyboardInterrupt):
        return None

    choice = choice.strip()
    if not choice or choice not in ("1", "2", "3", "4"):
        return None

    badge_markdown = generate_badge_markdown(grade, score, project_name)
    share_url = f"https://deepsweep.ai/badge/{project_name}"
    share_text = get_share_text_for_grade(grade, score)

    action: str | None = None

    if choice == "1":
        copied = _copy_to_clipboard(badge_markdown)
        click.echo()
        if copied:
            click.echo(f"{SYMBOL_PASS} Badge markdown copied to clipboard")
        else:
            click.echo(f"{SYMBOL_PASS} Badge markdown (copy manually):")
        click.echo()
        click.echo(click.style("  Paste this in your README.md:", dim=True))
        click.echo(f"  {badge_markdown}")
        click.echo()
        action = "badge_copied"

    elif choice == "2":
        url = get_twitter_url(share_text, share_url)
        _open_url(url)
        click.echo()
        click.echo(f"{SYMBOL_PASS} Opening X (Twitter)...")
        click.echo()
        action = "twitter_share"

    elif choice == "3":
        url = get_linkedin_url(share_url)
        _open_url(url)
        click.echo()
        click.echo(f"{SYMBOL_PASS} Opening LinkedIn...")
        click.echo()
        action = "linkedin_share"

    elif choice == "4":
        copied = _copy_to_clipboard(share_url)
        click.echo()
        if copied:
            click.echo(f"{SYMBOL_PASS} Share link copied to clipboard")
        else:
            click.echo(f"{SYMBOL_PASS} Share link: {share_url}")
        click.echo()
        action = "link_copied"

    # Track the action
    if action:
        with contextlib.suppress(Exception):
            from deepsweep.reputation.metrics import track_share_action

            track_share_action(
                action=action,
                platform=action.split("_")[0],
                score=score,
                tier="",
            )

    return action


def _get_share_headline(grade: str) -> str:
    """Get celebratory headline based on grade."""
    if grade in ("A+", "A"):
        return "Your code is ready to ship"
    elif grade in ("A-", "B+", "B"):
        return "Looking good -- ready with minor review"
    elif grade in ("B-", "C+", "C"):
        return "Solid foundation -- a few items to check"
    else:
        return "Room for improvement -- let's fix these"


def _open_url(url: str) -> None:
    """Open URL in default browser."""
    with contextlib.suppress(Exception):
        webbrowser.open(url)
