"""Social sharing command for reputation scores."""

import os
import subprocess

import click

from deepsweep.reputation.api_client import ReputationAPIClient
from deepsweep.reputation.local_store import LocalReputationStore


def _copy_to_clipboard(text: str) -> bool:
    """
    Copy text to clipboard (cross-platform).

    Returns:
        True if successful, False otherwise
    """
    try:
        # Try pbcopy (macOS)
        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

        # Try xclip (Linux)
        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

        # Try xsel (Linux alternative)
        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


@click.command()
@click.option(
    "--platform",
    type=click.Choice(["twitter", "linkedin", "all"]),
    default="twitter",
    help="Social platform to generate share text for",
)
@click.option(
    "--copy",
    is_flag=True,
    help="Copy share text to clipboard",
)
def share(platform: str, copy: bool) -> None:
    """
    Generate social share text for your security score.

    Examples:

    \b
        deepsweep share
        deepsweep share --platform linkedin
        deepsweep share --copy
    """
    # Load reputation data
    store = LocalReputationStore()
    data = store.load()

    if data.current_score == 0:
        click.echo(
            "[INFO] No score data found. Run 'deepsweep validate .' to check your code first."
        )
        return

    # Track share prompt shown
    from deepsweep.reputation.metrics import track_share_prompt

    track_share_prompt(
        score=data.current_score,
        tier=data.tier,
        context="cli_command",
    )

    # Generate share content
    offline_mode = os.environ.get("DEEPSWEEP_OFFLINE") == "1"
    client = ReputationAPIClient(offline_mode=offline_mode)

    response = client.generate_share(
        grade=data.last_grade or "A",
        score=data.current_score,
        streak_days=data.streak_days,
    )

    # Customize for platform
    if platform == "linkedin":
        share_text = f"""Building with AI? Here's my security check.

I ran DeepSweep on my project to make sure the code my AI assistant generated is actually safe.

Results:
- Score: {data.current_score}/100 (Grade {data.last_grade})
- {_get_tier_description(data.tier)}
- Time to check: 30 seconds

If you're using Cursor, Copilot, or Claude Code to build, this takes 30 seconds and could save you headaches.

Free tool: https://deepsweep.ai

#VibeCoding #AI #Startups #IndieHacker"""

    elif platform == "twitter":
        # Generate vibe-coder friendly Twitter text
        share_text = f"""Just checked my AI-built app for security issues 🔒

Score: {data.current_score}/100 (Grade {data.last_grade})
{_get_findings_summary(data.last_grade)}

Check your app free: deepsweep.ai

#VibeCoding #CursorAI #BuildInPublic"""

    else:  # all
        twitter_text = f"""Just checked my AI-built app for security issues 🔒

Score: {data.current_score}/100 (Grade {data.last_grade})
{_get_findings_summary(data.last_grade)}

Check your app free: deepsweep.ai

#VibeCoding #CursorAI #BuildInPublic"""

        linkedin_text = f"""Building with AI? Here's my security check.

I ran DeepSweep on my project to make sure the code my AI assistant generated is actually safe.

Results:
- Score: {data.current_score}/100 (Grade {data.last_grade})
- {_get_tier_description(data.tier)}
- Time to check: 30 seconds

If you're using Cursor, Copilot, or Claude Code to build, this could save you headaches.

Free tool: https://deepsweep.ai

#VibeCoding #AI #Startups"""

        click.echo("\n=== Twitter ===")
        click.echo(twitter_text)
        click.echo(f"\nShare URL: {response.share_url}")
        click.echo("\n=== LinkedIn ===")
        click.echo(linkedin_text)

        if copy:
            # Copy Twitter version by default
            if _copy_to_clipboard(twitter_text):
                click.echo("\n[PASS] Twitter text copied to clipboard")
            else:
                click.echo(
                    "\n[INFO] Could not copy to clipboard (install xclip or xsel on Linux)"
                )
        return

    # Display single platform
    click.echo("\n" + share_text)
    click.echo(f"\nShare URL: {response.share_url}")

    if copy:
        if _copy_to_clipboard(share_text):
            click.echo("\n[PASS] Share text copied to clipboard")

            # Track share action
            from deepsweep.reputation.metrics import track_share_action

            track_share_action(
                action="copy",
                platform=platform,
                score=data.current_score,
                tier=data.tier,
            )
        else:
            click.echo(
                "\n[INFO] Could not copy to clipboard (install xclip or xsel on Linux)"
            )

    # Show current status
    tier_emoji = {
        "diamond": "💎",
        "platinum": "🏆",
        "gold": "🥇",
        "silver": "🥈",
        "bronze": "🥉",
        "unverified": "🔰",
    }.get(data.tier, "")

    click.echo(f"\n{tier_emoji} Current Tier: {data.tier.title()}")

    if data.streak_days > 0:
        streak_emoji = "🔥" if data.streak_days >= 7 else "⚡"
        click.echo(
            f"{streak_emoji} Streak: {data.streak_days} day{'s' if data.streak_days != 1 else ''}"
        )


def _get_findings_summary(grade: str) -> str:
    """Get findings summary based on grade for Twitter."""
    summaries = {
        "A": "All clear! Ready to ship. ✅",
        "B": "Looks good. Minor things to check.",
        "C": "Found some issues. Easy fixes.",
        "D": "Needs work. Fixing now.",
        "F": "Critical issues found. Working on it.",
    }
    return summaries.get(grade, "Running security checks...")


def _get_tier_description(tier: str) -> str:
    """Get description for tier."""
    descriptions = {
        "diamond": "Security Legend (Top 1%)",
        "platinum": "Security Expert (Top 5%)",
        "gold": "Security Champion",
        "silver": "Security Pro",
        "bronze": "Security Aware",
        "unverified": "Getting Started",
    }
    return descriptions.get(tier, "")
