from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import json
import random
import re
from typing import Dict, Any

app = FastAPI()

# Add CORS middleware to allow requests from the frontend
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, replace with specific origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Simple in-memory user database
users = {}

# AI detection patterns
ai_patterns = [
    r"\b(therefore|thus|hence|consequently)\b",
    r"\b(in conclusion|to summarize|to sum up)\b",
    r"\b(firstly|secondly|thirdly|finally)\b",
    r"\b(it is \w+ that|it can be \w+ that)\b",
    r"\b(as (we|one) can see)\b",
    r"\b(this (essay|paper|article) (will|aims to))\b"
]

# Humanization techniques
humanization_techniques = [
    lambda text: text.replace("therefore", "because of this").replace("Therefore", "Because of this"),
    lambda text: text.replace("thus", "so").replace("Thus", "So"),
    lambda text: text.replace("hence", "that's why").replace("Hence", "That's why"),
    lambda text: text.replace("in conclusion", "to wrap things up").replace("In conclusion", "To wrap things up"),
    lambda text: text.replace("firstly", "first").replace("Firstly", "First"),
    lambda text: text.replace("secondly", "next").replace("Secondly", "Next"),
    lambda text: re.sub(r"it is (\w+) that", r"I think \1", text),
    lambda text: re.sub(r"as we can see", "it's clear", text),
    lambda text: re.sub(r"this (essay|paper|article) (will|aims to)", r"I'm going to", text),
    lambda text: add_filler_words(text),
    lambda text: vary_sentence_length(text)
]

def add_filler_words(text: str) -> str:
    """Add casual filler words to make text sound more human."""
    sentences = re.split(r'(?<=[.!?])\s+', text)
    modified_sentences = []
    
    filler_words = ["actually", "basically", "honestly", "I mean", "you know", "like", "sort of", "kind of"]
    
    for i, sentence in enumerate(sentences):
        if random.random() < 0.3:  # 30% chance to add a filler word
            filler = random.choice(filler_words)
            if random.random() < 0.5:  # 50% chance to add at beginning
                sentence = f"{filler}, {sentence[0].lower()}{sentence[1:]}"
            else:  # 50% chance to add in middle
                words = sentence.split()
                if len(words) > 4:
                    mid_point = len(words) // 2
                    words.insert(mid_point, filler)
                    sentence = " ".join(words)
        modified_sentences.append(sentence)
    
    return " ".join(modified_sentences)

def vary_sentence_length(text: str) -> str:
    """Vary sentence length to sound more human."""
    sentences = re.split(r'(?<=[.!?])\s+', text)
    modified_sentences = []
    
    for i, sentence in enumerate(sentences):
        words = sentence.split()
        
        # For longer sentences, consider breaking them up
        if len(words) > 20 and random.random() < 0.7:
            mid_point = len(words) // 2
            # Find a good breaking point near the middle
            for j in range(mid_point - 3, mid_point + 3):
                if j > 0 and j < len(words) and words[j] not in ["and", "or", "but", "because", "that"]:
                    first_part = " ".join(words[:j]) + "."
                    second_part = " ".join([words[j][0].upper() + words[j][1:]] + words[j+1:])
                    modified_sentences.append(first_part)
                    modified_sentences.append(second_part)
                    break
            else:
                modified_sentences.append(sentence)
        else:
            modified_sentences.append(sentence)
    
    return " ".join(modified_sentences)

def detect_ai_text(text: str) -> Dict[str, Any]:
    """Detect if text was likely written by AI."""
    ai_score = 0
    total_patterns = len(ai_patterns)
    detected_patterns = []
    
    for pattern in ai_patterns:
        matches = re.findall(pattern, text, re.IGNORECASE)
        if matches:
            ai_score += len(matches)
            detected_patterns.extend(matches)
    
    # Calculate percentage based on number of patterns found
    percentage = min(100, int((ai_score / max(1, len(text.split()) / 20)) * 100))
    
    return {
        "score": percentage,
        "isAI": percentage > 30,
        "confidence": "high" if percentage > 70 else "medium" if percentage > 40 else "low",
        "detectedPatterns": list(set(detected_patterns))[:5]  # Limit to 5 unique patterns
    }

def humanize_text(text: str) -> str:
    """Apply humanization techniques to make AI text sound more human."""
    result = text
    
    # Apply a random subset of techniques
    techniques = random.sample(humanization_techniques, min(5, len(humanization_techniques)))
    for technique in techniques:
        result = technique(result)
    
    return result

@app.post("/command")
async def handle_command(request: Request):
    data = await request.json()
    command = data.get("command")
    
    if command == "signup":
        email = data.get("email")
        password = data.get("password")
        
        # Check if user already exists
        if email in users:
            return {"success": False, "message": "User already exists"}
        
        # Store user in our simple database
        users[email] = {"email": email, "password": password}
        
        # Return success response with user data and token
        return {
            "success": True,
            "user": {
                "email": email,
                "token": "dummy-token-for-" + email
            },
            "subscriptionPlan": "Basic",  # Default subscription
            "freeTrial": True
        }
    
    elif command == "login":
        email = data.get("email")
        password = data.get("password")
        
        # Check if user exists and password matches
        if email in users and users[email]["password"] == password:
            return {
                "success": True,
                "user": {
                    "email": email,
                    "token": "dummy-token-for-" + email
                },
                "subscriptionPlan": "Basic",
                "freeTrial": True
            }
        else:
            return {"success": False, "message": "Invalid email or password"}
    
    elif command == "detect":
        text = data.get("text", "")
        if not text:
            return {"success": False, "message": "No text provided"}
        
        result = detect_ai_text(text)
        return {
            "success": True,
            "result": result
        }
    
    elif command == "humanize":
        text = data.get("text", "")
        if not text:
            return {"success": False, "message": "No text provided"}
        
        humanized_text = humanize_text(text)
        return {
            "success": True,
            "processed": humanized_text
        }
    
    # Handle unknown commands
    return {"success": False, "message": f"Unknown command: {command}"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8001)