#!/usr/bin/env python3
import base64
import json
import os
import sys
import urllib.request
import urllib.parse

BASE_DIR = "/var/www/html"
ENV_FILE = BASE_DIR + "/.env.spotify"
SEED_FILE = BASE_DIR + "/seeds/songs.txt"


def load_env():
    env = {}
    with open(ENV_FILE, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            if "=" in line:
                k, v = line.split("=", 1)
                env[k.strip()] = v.strip()
    return env


def get_token(client_id, client_secret):
    auth = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
    data = urllib.parse.urlencode({"grant_type": "client_credentials"}).encode()

    req = urllib.request.Request(
        "https://accounts.spotify.com/api/token",
        data=data,
        headers={
            "Authorization": f"Basic {auth}",
            "Content-Type": "application/x-www-form-urlencoded",
        },
    )

    with urllib.request.urlopen(req) as r:
        return json.loads(r.read().decode("utf-8"))["access_token"]


def api(url, token):
    req = urllib.request.Request(
        url,
        headers={"Authorization": f"Bearer {token}"}
    )
    with urllib.request.urlopen(req) as r:
        return json.loads(r.read().decode("utf-8"))


def search_artist(name, token):
    url = (
        "https://api.spotify.com/v1/search?q="
        + urllib.parse.quote(name)
        + "&type=artist&limit=1"
    )
    data = api(url, token)

    items = data.get("artists", {}).get("items", [])
    if not items:
        print("Sanatçı bulunamadı")
        sys.exit(1)

    return items[0]["id"], items[0]["name"]


def get_albums(artist_id, token):
    albums = []
    url = (
        f"https://api.spotify.com/v1/artists/{artist_id}/albums"
        "?include_groups=album,single&limit=50"
    )

    while url:
        data = api(url, token)
        albums.extend(data.get("items", []))
        url = data.get("next")

    return albums


def get_tracks(album_id, token):
    tracks = []
    url = f"https://api.spotify.com/v1/albums/{album_id}/tracks?limit=50"

    while url:
        data = api(url, token)
        tracks.extend(data.get("items", []))
        url = data.get("next")

    return tracks


def main():
    if len(sys.argv) < 2:
        print('Kullanım: python3 import_spotify_artist.py "Sanatçı Adı"')
        sys.exit(1)

    artist_input = " ".join(sys.argv[1:])

    env = load_env()
    client_id = env.get("SPOTIFY_CLIENT_ID")
    client_secret = env.get("SPOTIFY_CLIENT_SECRET")

    if not client_id or not client_secret:
        print(".env.spotify içinde SPOTIFY_CLIENT_ID veya SPOTIFY_CLIENT_SECRET eksik")
        sys.exit(1)

    token = get_token(client_id, client_secret)

    artist_id, artist_name = search_artist(artist_input, token)
    print("Sanatçı bulundu:", artist_name)

    albums = get_albums(artist_id, token)
    print("Albüm/single sayısı:", len(albums))

    songs = set()

    for album in albums:
        tracks = get_tracks(album["id"], token)
        for t in tracks:
            track_name = t["name"].strip()
            if track_name:
                songs.add(f"{artist_name} - {track_name}")

    songs = sorted(songs)

    print("Toplam benzersiz şarkı:", len(songs))

    os.makedirs(os.path.dirname(SEED_FILE), exist_ok=True)

    with open(SEED_FILE, "a", encoding="utf-8") as f:
        for s in songs:
            f.write(s + "\n")

    print(f"{SEED_FILE} içine eklendi ✔")


if __name__ == "__main__":
    main()