import argparse
from pathlib import Path
from flask import Flask, render_template, request, jsonify
from marco.core import repository
import json

app = Flask(__name__)
REPO_PATH = Path.cwd()

@app.route('/')
def index():
    try:
        versions = repository.list_versions(REPO_PATH)
    except Exception:
        versions = []
    return render_template('index.html', versions=versions)

@app.route('/version/<vid>')
def version_detail(vid):
    repo_path = REPO_PATH
    try:
        resolved_vid = repository.resolve_version(vid, repo_path)
    except ValueError:
        return "Version not found", 404
        
    v_dir = repo_path / '.marco' / 'versions' / resolved_vid
    manifest = json.loads((v_dir / 'manifest.json').read_text(encoding='utf-8'))
    metrics = json.loads((v_dir / 'metrics.json').read_text(encoding='utf-8'))
    config = json.loads((v_dir / 'config.json').read_text(encoding='utf-8'))
    
    tags = repository.list_tags(repo_path)
    v_tags = [t for t, v in tags.items() if v == resolved_vid]
    
    return render_template('version.html', manifest=manifest, metrics=metrics, config=config, tags=v_tags)

@app.route('/api/versions')
def api_versions():
    return jsonify(repository.list_versions(REPO_PATH))

def main():
    parser = argparse.ArgumentParser(description="Marco Web Dashboard")
    parser.add_argument("--port", type=int, default=5000)
    parser.add_argument("--repo", type=str, default=".")
    args = parser.parse_args()
    
    global REPO_PATH
    REPO_PATH = Path(args.repo).resolve()
    
    app.run(port=args.port, debug=True)

if __name__ == "__main__":
    main()
