<?php
// /tag-extractor/process.php
header('Content-Type: application/json; charset=utf-8');

function cleanText($text) {
    // Strip basic HTML tags, RTF clutter, etc.
    // Simple cleanup; you can expand this if needed.
    // Remove RTF header stuff:
    $text = preg_replace('/{\\\rtf1.*?{\\\fonttbl.*?}}/s', ' ', $text);
    $text = strip_tags($text);
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    return $text;
}

function extractTagsFromText($text) {
    $text = cleanText($text);

    // @handles
    preg_match_all('/@([A-Za-z0-9_\.]+)/u', $text, $handlesMatches);
    $handles = $handlesMatches[0];

    // #hashtags
    preg_match_all('/#(\w+)/u', $text, $hashtagsMatches);
    $hashtags = $hashtagsMatches[0];

    // URLs
    preg_match_all('/https?:\/\/[^\s"<>\']+/i', $text, $urlMatches);
    $links = $urlMatches[0];

    // emails
    preg_match_all('/[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/', $text, $emailMatches);
    $emails = $emailMatches[0];

    // Deduplicate and sort
    $handles = array_values(array_unique($handles));
    $hashtags = array_values(array_unique($hashtags));
    $links = array_values(array_unique($links));
    $emails = array_values(array_unique($emails));

    sort($handles);
    sort($hashtags);
    sort($links);
    sort($emails);

    return [
        'handles' => $handles,
        'hashtags' => $hashtags,
        'links' => $links,
        'emails' => $emails,
        'text_length' => mb_strlen($text, 'UTF-8')
    ];
}

$mode = $_POST['mode'] ?? '';

if ($mode === 'file') {
    if (!isset($_FILES['tagfile']) || $_FILES['tagfile']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['error' => 'File upload failed.']);
        exit;
    }

    $tmpPath = $_FILES['tagfile']['tmp_name'];
    $contents = file_get_contents($tmpPath);
    if ($contents === false) {
        echo json_encode(['error' => 'Could not read uploaded file.']);
        exit;
    }

    $result = extractTagsFromText($contents);
    echo json_encode($result);
    exit;

} elseif ($mode === 'url') {
    $url = trim($_POST['source_url'] ?? '');
    if (empty($url)) {
        echo json_encode(['error' => 'URL is required.']);
        exit;
    }

    // Basic validation
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        echo json_encode(['error' => 'Invalid URL.']);
        exit;
    }

    // Simple fetch – note: sites can block this, and user is responsible for ToS
    $context = stream_context_create([
        'http' => [
            'timeout' => 10,
            'user_agent' => 'Studio1LiveTagExtractor/1.0'
        ]
    ]);

    $html = @file_get_contents($url, false, $context);
    if ($html === false) {
        echo json_encode(['error' => 'Unable to fetch URL (blocked or unreachable).']);
        exit;
    }

    $result = extractTagsFromText($html);
    echo json_encode($result);
    exit;
}

echo json_encode(['error' => 'Invalid mode.']);
exit;
