"""Chapter quiz runner for the 60-day Python course.

Usage:
    python quiz.py           -> shows your progress
    python quiz.py 3         -> takes the test for chapter 3 (Days 11-15)
    python quiz.py all       -> takes every test in order

Pass mark: 4 out of 5. Results are saved in progress.json next to this file.
"""
import json
import sys
from pathlib import Path

PASS_MARK = 4
PROGRESS_FILE = Path(__file__).with_name("progress.json")

# (title, [(question, [options], index_of_correct_option)])
CHAPTERS = {
    1: ("Days 1-5: Basics, numbers, text", [
        ("What does 7 // 2 give?", ["3.5", "3", "4", "1"], 1),
        ("What is the type of \"42\" (with quotes)?", ["int", "float", "str", "bool"], 2),
        ("What is \"Python\"[-1]?", ["P", "n", "o", "y"], 1),
        ("Which is a valid variable name?", ["2name", "my name", "my_name", "my-name"], 2),
        ("What does \"  hi \".strip() return?", ["\"hi\"", "\"  hi\"", "\"hi \"", "an error"], 0),
    ]),
    2: ("Days 6-10: Input and decisions", [
        ("What type does input() always return?", ["int", "float", "str", "bool"], 2),
        ("What is the difference between = and ==?", ["none", "= assigns, == compares", "= compares, == assigns", "both assign"], 1),
        ("score = 70; if >=90 'A' elif >=60 'B' else 'C'. Result?", ["A", "B", "C", "error"], 1),
        ("What is True and False?", ["True", "False", "None", "error"], 1),
        ("How does Python mark a block of code?", ["curly braces", "indentation", "semicolons", "END keyword"], 1),
    ]),
    3: ("Days 11-15: Lists and loops", [
        ("fruits = ['a','b','c']; what is fruits[-1]?", ["a", "b", "c", "error"], 2),
        ("What does range(1, 6) produce?", ["1 to 6", "1 to 5", "0 to 5", "0 to 6"], 1),
        ("Which keyword stops a loop completely?", ["continue", "pass", "break", "stop"], 2),
        ("What does list.append(x) do?", ["adds x at the end", "adds x at the start", "removes x", "sorts the list"], 0),
        ("a = [1]; b = a; b.append(2). What is a?", ["[1]", "[1, 2]", "[2]", "error"], 1),
    ]),
    4: ("Days 16-20: Sets, dicts, functions", [
        ("What does set([1,1,2]) keep?", ["[1,1,2]", "{1, 2}", "{1,1,2}", "error"], 1),
        ("d = {'a': 1}; d.get('z', 0) returns?", ["error", "None", "0", "1"], 2),
        ("Tuples are...", ["changeable", "unchangeable (immutable)", "unordered", "only numbers"], 1),
        ("What does return do in a function?", ["prints the value", "gives the value back to the caller", "deletes the function", "loops"], 1),
        ("A variable created inside a function is visible...", ["everywhere", "only inside that function", "in other files", "never"], 1),
    ]),
    5: ("Days 21-25: Errors, files, CSV, JSON", [
        ("[n*2 for n in [1,2,3]] equals?", ["[1,2,3]", "[2,4,6]", "[2,3,4]", "6"], 1),
        ("Which line catches the error from int('abc')?", ["except ValueError:", "except KeyError:", "except IndexError:", "except FileError:"], 0),
        ("Which file mode adds text without erasing the file?", ["r", "w", "a", "x"], 2),
        ("Values read from a CSV file are...", ["numbers", "strings", "booleans", "lists"], 1),
        ("json.dump vs json.dumps?", ["same thing", "dump writes to a file, dumps returns a string", "dump returns a string, dumps writes a file", "dumps is for lists only"], 1),
    ]),
    6: ("Days 26-30: Modules, venv, files, project", [
        ("Command to install a library?", ["python install x", "pip install x", "import install x", "get x"], 1),
        ("What does datetime.now() return?", ["only the time", "only the date", "current date and time", "a string"], 2),
        ("Why use a virtual environment?", ["to run faster", "to keep each project's libraries separate", "to hide code", "it is required by Windows"], 1),
        ("Path('report.txt').suffix is...", ["report", ".txt", "txt", "report.txt"], 1),
        ("Before moving many files in a script, you should...", ["run it on real files immediately", "do a dry run that only prints what it would do", "delete the originals", "skip testing"], 1),
    ]),
    7: ("Days 31-35: Classes and regex", [
        ("When does __init__ run?", ["when the file is saved", "when an object is created", "when the program ends", "never automatically"], 1),
        ("self refers to...", ["the class file", "the current object", "the parent class", "Python itself"], 1),
        ("class B(A): means...", ["B contains A", "B inherits from A", "A inherits from B", "B deletes A"], 1),
        ("@dataclass mainly saves you from...", ["writing boilerplate like __init__", "installing packages", "writing loops", "debugging"], 0),
        ("re.findall(r'\\d+', 'a12b345') returns?", ["['12', '345']", "['1','2','3','4','5']", "12345", "[]"], 0),
    ]),
    8: ("Days 36-40: Debugging, testing, functional tools", [
        ("pytest test function names must start with...", ["check_", "test_", "run_", "pytest_"], 1),
        ("If assert x == 3 is false, the test...", ["passes", "fails", "is skipped", "deletes x"], 1),
        ("logging.exception() records...", ["only a message", "the message plus the full traceback", "nothing", "only the time"], 1),
        ("sorted(people, key=lambda p: p[1]) sorts by...", ["first item", "second item", "length", "name"], 1),
        ("Which keyword makes a function a generator?", ["return", "yield", "gen", "async"], 1),
    ]),
    9: ("Days 41-45: APIs, scraping, Excel", [
        ("HTTP status 404 means...", ["success", "not found", "server crashed", "not allowed"], 1),
        ("Where should API keys live?", ["in the code", "in a .env file that is not committed", "in the README", "in the URL"], 1),
        ("What should every requests.get call include?", ["a timeout", "a password", "a loop", "print"], 0),
        ("BeautifulSoup is used to...", ["send email", "parse HTML", "draw charts", "run SQL"], 1),
        ("openpyxl works with...", ["PDF files", "Excel .xlsx files", "images", "audio"], 1),
    ]),
    10: ("Days 46-50: Email, pandas, charts", [
        ("For Gmail SMTP you should use...", ["your normal password", "an App Password", "no password", "your phone number"], 1),
        ("df.head() shows...", ["the last 5 rows", "the first 5 rows", "column names only", "statistics"], 1),
        ("df.groupby('customer')['amount'].sum() gives...", ["total per customer", "count of customers", "the biggest amount", "an error"], 0),
        ("df.dropna() removes...", ["duplicate rows", "rows with missing values", "all columns", "text"], 1),
        ("Best chart for a trend over time?", ["line chart", "pie chart", "none", "table only"], 0),
    ]),
    11: ("Days 51-55: Databases, FastAPI, scheduling, bots", [
        ("Using ? placeholders in SQL protects against...", ["slow queries", "SQL injection", "typos", "disk errors"], 1),
        ("uvicorn main:app --reload does what?", ["installs FastAPI", "runs your API with auto-restart", "deploys to the cloud", "runs tests"], 1),
        ("FastAPI gives automatic interactive docs at...", ["/docs", "/help", "/api-docs", "/swagger.py"], 0),
        ("Which Windows tool runs a script on a schedule?", ["Task Scheduler", "Paint", "Registry", "Notepad"], 0),
        ("Where should a Discord bot token go?", ["in the code", "in .env, never shared", "in a public repo", "in the chat"], 1),
    ]),
    12: ("Days 56-60: Async, Git, structure", [
        ("await can only be used inside...", ["any function", "async def", "a class only", "a loop only"], 1),
        ("asyncio.gather(...) does what?", ["runs tasks one after another", "runs tasks concurrently", "stops tasks", "sorts tasks"], 1),
        ("Which should be in .gitignore?", [".env and .venv/", "main.py", "README.md", "requirements.txt"], 0),
        ("git commit does what?", ["uploads to GitHub", "saves a snapshot in local history", "deletes files", "installs packages"], 1),
        ("if __name__ == '__main__': is used to...", ["run code only when the file is executed directly", "import modules", "make code faster", "hide code"], 0),
    ]),
}


def load_progress():
    try:
        return json.loads(PROGRESS_FILE.read_text(encoding="utf-8"))
    except (FileNotFoundError, json.JSONDecodeError):
        return {}


def save_progress(progress):
    PROGRESS_FILE.write_text(json.dumps(progress, indent=2), encoding="utf-8")


def ask(question, options):
    print(f"\n{question}")
    for i, option in enumerate(options):
        print(f"  {'ABCD'[i]}) {option}")
    while True:
        answer = input("Your answer (A-D): ").strip().upper()
        if answer in ("A", "B", "C", "D"):
            return "ABCD".index(answer)
        print("Please type A, B, C or D.")


def run_chapter(number, progress):
    title, questions = CHAPTERS[number]
    print(f"\n=== Chapter {number} test: {title} ===")
    score = 0
    for question, options, correct in questions:
        if ask(question, options) == correct:
            print("  Correct!")
            score += 1
        else:
            print(f"  Not quite. Answer: {'ABCD'[correct]}) {options[correct]}")
    passed = score >= PASS_MARK
    best = max(score, progress.get(str(number), {}).get("best", 0))
    progress[str(number)] = {"best": best, "passed": passed or progress.get(str(number), {}).get("passed", False)}
    save_progress(progress)
    print(f"\nScore: {score}/{len(questions)}  ->  {'PASSED' if passed else 'Review the chapter and try again'}")


def show_progress(progress):
    print("Your progress:")
    for number, (title, _) in CHAPTERS.items():
        info = progress.get(str(number))
        status = "not taken" if not info else f"best {info['best']}/5 {'(passed)' if info['passed'] else '(retry)'}"
        print(f"  Chapter {number:>2}  {title:<55} {status}")


def main():
    progress = load_progress()
    if len(sys.argv) < 2:
        show_progress(progress)
        print("\nRun: python quiz.py <chapter number>   or   python quiz.py all")
        return
    arg = sys.argv[1].lower()
    if arg == "all":
        for number in CHAPTERS:
            run_chapter(number, progress)
    elif arg.isdigit() and int(arg) in CHAPTERS:
        run_chapter(int(arg), progress)
    else:
        print("Chapter must be 1 to 12, or 'all'.")


if __name__ == "__main__":
    main()
