import argparse
import os
from docx import Document
from autodocz.generator import make_readme, make_license, make_report, set_api_key
from autodocz.utils import *

def main():
    parser = argparse.ArgumentParser(
        prog="autodocz",
        description="autodocz: directory tree & doc generator"
    )
    sub = parser.add_subparsers(dest="command", required=True)

    # GENERATE command
    gen = sub.add_parser("generate", help="generate documentation files")
    gen.add_argument("doc", choices=["readme", "license", "srs", "report", "all"],
                     help="which document to generate")
    gen.add_argument("-o", "--output", default=None,
                     help="path/filename to write (default: README.md, LICENSE, REPORT.docx)")
    gen.add_argument("-k", "--api-key", dest="api_key",
                     help="your GROQ API key (overrides GROQ_API_KEY env var)")

    args = parser.parse_args()

    # inject API key if provided
    if getattr(args, "api_key", None):
        set_api_key(args.api_key)

    if args.command == "generate":
        review_data = get_project_review() if args.doc in ("readme", "report", "all") else None
        targets = [args.doc] if args.doc != "all" else ["readme", "license", "report"]

        for doc in targets:
            if doc == "readme":
                content = make_readme(review_data)
                out = args.output or "README.md"
                with open(out, "w") as f:
                    f.write(content)
                print(f"✅ Generated {out}")

            elif doc == "license":
                content = make_license()
                out = args.output or "LICENSE"
                with open(out, "w") as f:
                    f.write(content)
                print(f"✅ Generated {out}")

            elif doc == "report":
                report_text = make_report(review_data)
                docx = Document()
                docx.add_paragraph(report_text)
                out = args.output or "REPORT.docx"
                docx.save(out)
                print(f"✅ Generated {out}")
