# VERSION: 1.1
# AUTHORS: Naru
#
# Internet Archive (archive.org) search plugin.
# 공개 도메인 / 크리에이티브 커먼즈 등 합법 콘텐츠만 색인하는 archive.org 를
# 검색한다. 각 아이템은 archive.org 가 직접 시딩하는 .torrent 로 제공된다.

import datetime
import json
from urllib.parse import quote

from helpers import retrieve_url
from novaprinter import prettyPrinter


def _to_unix(value):
    """archive.org publicdate(ISO8601) → Unix 초. 실패하면 -1."""
    if isinstance(value, list):
        value = value[0] if value else ''
    if isinstance(value, str) and len(value) >= 19:
        try:
            dt = datetime.datetime.strptime(value[:19], '%Y-%m-%dT%H:%M:%S')
            return int(dt.replace(tzinfo=datetime.timezone.utc).timestamp())
        except Exception:
            return -1
    return -1


class internetarchive:
    url = 'https://archive.org'
    name = 'Internet Archive'
    supported_categories = {'all': ''}

    def search(self, what: str, cat: str = 'all') -> None:
        query = what.replace('+', ' ')
        api = (
            'https://archive.org/advancedsearch.php?q='
            + quote('(' + query + ') AND mediatype:(movies OR audio OR texts OR software OR data OR image)')
            + '&fl[]=identifier&fl[]=title&fl[]=item_size&fl[]=downloads&fl[]=publicdate'
            + '&sort[]=downloads+desc&rows=60&page=1&output=json'
        )
        try:
            data = json.loads(retrieve_url(api))
        except Exception:
            return

        for doc in data.get('response', {}).get('docs', []):
            ident = doc.get('identifier')
            if not ident:
                continue
            title = doc.get('title', ident)
            if isinstance(title, list):
                title = title[0] if title else ident
            size = doc.get('item_size', 0) or 0
            torrent = 'https://archive.org/download/{0}/{0}_archive.torrent'.format(ident)
            prettyPrinter({
                'link': torrent,
                'name': str(title),
                'size': str(size) + ' B',
                'seeds': -1,
                'leech': -1,
                'engine_url': self.url,
                'desc_link': 'https://archive.org/details/' + ident,
                'pub_date': _to_unix(doc.get('publicdate', '')),
            })
