import os
import random

import psycopg
from dotenv import load_dotenv
from faker import Faker

_ = load_dotenv()

USERNAME = os.getenv("USERNAME")
PASSWORD = os.getenv("PASSWORD")

CONNSTR = (
    f"host=data.cs.jmu.edu port=5432 dbname=sec2 user={USERNAME} password={PASSWORD}"
)

fake = Faker()


def make_releases() -> list[tuple[int, str, str, float, int]]:
    releases: list[tuple[int, str, str, float, int]] = []

    for i in range(0, 20):
        title = fake.bs()
        format = "CD"
        sample_rate = 44.1
        release_year = int(fake.year())

        releases.append((i, title, format, sample_rate, release_year))

    return releases


def make_tracks() -> list[tuple[int, str, float, str, int]]:
    tracks: list[tuple[int, str, float, str, int]] = []

    for i in range(0, 20):
        title = fake.bs()
        duration_sec = random.uniform(0.0, 1200.0)
        track_artist = fake.name()
        release_id = random.randint(0, 19)

        tracks.append((i, title, duration_sec, track_artist, release_id))

    return make_tracks()


def create_tables(cur: psycopg.Cursor):
    with psycopg.connect(CONNSTR) as conn:
        with conn.cursor() as cur:
            _ = cur.execute(
                """
                CREATE TABLE IF NOT EXISTS Release (
                    id INTEGER PRIMARY KEY,
                    title TEXT NOT NULL,
                    format TEXT NOT NULL,
                    sample_rate_khz REAL,
                    release_year INTEGER NOT NULL
                )
                """
            )

            _ = cur.execute(
                """
                CREATE TABLE IF NOT EXISTS Track (
                    id INTEGER PRIMARY KEY,
                    title TEXT NOT NULL,
                    duration_sec REAL NOT NULL,
                    track_artist TEXT,
                    release_id INTEGER,
                    FOREIGN KEY (release_id) REFERENCES Release(id)
                )
                """
            )

        conn.commit()


def insert_table1():
    with psycopg.connect(CONNSTR) as conn:
        with conn.cursor() as cur:
            cur.executemany(
                """
                INSERT INTO Release (id, title, format, sample_rate_khz, release_year)
                VALUES (%s, %s, %s, %s, %s)
            """,
                make_releases(),
            )

        conn.commit()


def insert_table2():
    with psycopg.connect(CONNSTR) as conn:
        with conn.cursor() as cur:
            cur.executemany(
                """
                INSERT INTO Track (id, title, duration_sec, track_artist, release_id)
                VALUES (%s, %s, %s, %s, %s)
            """,
                make_tracks(),
            )

        conn.commit()


if __name__ == "__main__":
    # Connect to postgres and create a cursor
    with psycopg.connect(CONNSTR) as conn:
        with conn.cursor() as cur:
            create_tables(cur)
