#!/usr/bin/env python3
"""
TinyURL MCP Server
ProvideURL缩短和管理功能
"""

import json
import requests
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("TinyURL Link Shortener")

@mcp.tool()
def create_short_url(url: str, alias: str = None):
    """创建短链接"""
    api_url = "https://tinyurl.com/api-create.php"
    params = {
        "url": url
    }
    
    if alias:
        params["alias"] = alias
    
    try:
        response = requests.get(api_url, params=params, timeout=10)
        
        if response.status_code == 200:
            result = response.text.strip()
            
            # 检查是否ReturnError
            if result.startswith("Error"):
                return {"error": result}
            elif result.startswith("http"):
                return {
                    "original_url": url,
                    "short_url": result,
                    "alias": alias,
                    "success": True
                }
            else:
                return {"error": f"意外的Response: {result}"}
        else:
            return {"error": f"API调用Failed: HTTP {response.status_code}"}
    except Exception as e:
        return {"error": f"创建短链接Failed: {str(e)}"}

@mcp.tool()
def create_custom_short_url(url: str, custom_alias: str):
    """创建自定义别名的短链接"""
    return create_short_url(url, custom_alias)

@mcp.tool()
def validate_url(url: str):
    """验证URL是否有效"""
    try:
        # 检查URL格式
        if not url.startswith(('http://', 'https://')):
            return {
                "url": url,
                "valid": False,
                "error": "URL必须以http://或https://开头"
            }
        
        # 尝试访问URL
        response = requests.head(url, timeout=10, allow_redirects=True)
        
        return {
            "url": url,
            "valid": True,
            "status_code": response.status_code,
            "final_url": response.url,
            "content_type": response.headers.get("Content-Type", ""),
            "content_length": response.headers.get("Content-Length", "")
        }
    except requests.exceptions.RequestException as e:
        return {
            "url": url,
            "valid": False,
            "error": f"URL无法访问: {str(e)}"
        }
    except Exception as e:
        return {
            "url": url,
            "valid": False,
            "error": f"验证Failed: {str(e)}"
        }

@mcp.tool()
def batch_create_short_urls(urls: list):
    """批量创建短链接"""
    if len(urls) > 50:
        return {"error": "批量Handle/ProcessAt mostSupport50个URL"}
    
    results = []
    for url in urls:
        result = create_short_url(url.strip())
        results.append({
            "original_url": url.strip(),
            "result": result
        })
        
        # 添加延迟避免Request过快
        import time
        time.sleep(0.5)
    
    return {
        "batch_results": results,
        "total_processed": len(results),
        "successful": len([r for r in results if r["result"].get("success")])
    }

@mcp.tool()
def get_url_info(short_url: str):
    """Get/Fetch短链接Info/Information（通过重定向检查）"""
    try:
        # 发送HEADRequestGet/Fetch重定向Info/Information
        response = requests.head(short_url, allow_redirects=False, timeout=10)
        
        if response.status_code in [301, 302, 303, 307, 308]:
            original_url = response.headers.get("Location", "")
            return {
                "short_url": short_url,
                "original_url": original_url,
                "status_code": response.status_code,
                "redirect_type": "temporary" if response.status_code in [302, 303, 307] else "permanent"
            }
        else:
            return {
                "short_url": short_url,
                "error": f"不是有效的重定向，状态码: {response.status_code}"
            }
    except Exception as e:
        return {
            "short_url": short_url,
            "error": f"Get/FetchInfo/InformationFailed: {str(e)}"
        }

@mcp.tool()
def expand_short_url(short_url: str):
    """展开短链接Get/Fetch原始URL"""
    try:
        response = requests.head(short_url, allow_redirects=True, timeout=10)
        
        return {
            "short_url": short_url,
            "expanded_url": response.url,
            "status_code": response.status_code,
            "redirect_chain": response.history and len(response.history) or 0
        }
    except Exception as e:
        return {
            "short_url": short_url,
            "error": f"展开链接Failed: {str(e)}"
        }

@mcp.tool()
def check_url_safety(url: str):
    """检查URL安全性（基础检查）"""
    try:
        # 基础安全检查
        suspicious_domains = [
            "bit.ly", "tinyurl.com", "goo.gl", "t.co", "short.link"
        ]
        
        # 检查是否是已知的短链接服务
        is_short_link = any(domain in url.lower() for domain in suspicious_domains)
        
        # 尝试Get/Fetch最终URL
        response = requests.head(url, allow_redirects=True, timeout=10)
        final_url = response.url
        
        # 检查重定向次数
        redirect_count = len(response.history)
        
        return {
            "url": url,
            "final_url": final_url,
            "is_short_link": is_short_link,
            "redirect_count": redirect_count,
            "status_code": response.status_code,
            "safety_notes": [
                "这只是基础检查",
                "请Use/Using专业安全工具进行完整扫描",
                f"重定向次数: {redirect_count}"
            ]
        }
    except Exception as e:
        return {
            "url": url,
            "error": f"安全检查Failed: {str(e)}"
        }

@mcp.tool()
def get_service_info():
    """Get/FetchTinyURL服务Info/Information"""
    return {
        "service": "TinyURL",
        "description": "FreeURL缩短服务",
        "features": [
            "URL缩短",
            "自定义别名",
            "批量Handle/Process",
            "链接验证",
            "重定向检查"
        ],
        "limitations": [
            "Free服务无Use/Using统计",
            "自定义别名可能被占用",
            "无API密钥管理功能"
        ],
        "api_endpoint": "https://tinyurl.com/api-create.php",
        "supported_protocols": ["http", "https"],
        "note": "Free服务，无需Register或API密钥",
        "documentation": "https://tinyurl.com/app/dev"
    }

if __name__ == "__main__":
    mcp.run() 